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.
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database