Win a copy of Production-Ready Serverless (Operational Best Practices) this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

Can't minus 1000 from short  RSS feed

 
Ranch Hand
Posts: 163
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i just cant work out how tominus 1000 from a short

i keep getting a short int error despite both variables being shorts

tried this:
engineSizeCharge = engineSize - (short)1000;      --    throws me an error
so i created a short variable and it still complains
why is java minus an int when i declared my variable as a short?


 
wayne brandon
Ranch Hand
Posts: 163
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
damn shorts again campbell i know...sigh
 
Marshal
Posts: 63781
209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is why you should use trousersints for your arithmetic. If you go through the Java┬« Language Specification (=JLS), you will find that the operands are converted to ints, which is what the bit about promotion means. Well, 1000 already is an int, but your short is also converted and the result is in the form of an int; you cannot fit an int into the 16 bits you have got available for a short. You have to cast it:-You need the () in those places because the precedence of casting is higher than + or -.
If you go through the JLS, you will find the same occurs for most arithmetical operators, which is why shorts are only suitable for exposing your knees to the sunshine. You will find that operators like += and -= don't require a cast, but they are liable to produce surprising results because they behave as if they embodied a cast. The only operators likely to be predictable are ++ and --, as long as you remember when overflow occurs.
Now you know why we have been ranting about shorts and bytes. The fact that those datatypes are “wide enough” to hold the range of values you have got doesn't mean they are suitable for general use.
 
Amateurs built google. Professionals built the titanic. We can't find the guy that built this tiny ad:
global solutions you can do at home or in your backyard
https://www.kickstarter.com/projects/paulwheaton/better-world-boo
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!