Another Example

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

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

C:/Private>

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.

QUESTION 5:

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