go to previous page   go to home page   hear noise   go to next page


Not in this example. But sometimes it does, when values are close to the limit of what can be represented in 16 bits.

Another Example

Here is another example:

short x = 12;
short y = 3;
short value;

value = x / y;

The expression   x / y   divides a 32-bit 12 by a 32-bit 3, even though the variables x and y are only 16 bits wide. The calculation produces a 32-bit result. Because the 32-bit result does not fit in the 16 bits of value the compiler will not compile the last statement. This can be completely baffling when it happens to you.

C:/Private>javac ShortStuff.java
ShortStuff.java:9: possible loss of precision
found   : int
required: short
    result = x / y;
1 error


At the professional programming level, details like these are sometimes important. But mostly for general purpose programs use int or long for integers and double for floating point. This will keep you out of trouble. If you can't avoid the problem, use a type cast, as described in chapter 28.


Do you expect that a modern electronic calculator will give you the same answer as Java for the expression  (31.5 - 12)/4.1 ?