Read this chapter, which discusses arithmetic operations in greater detail along with solving expressions with mixed data types.
5. Another Example
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 value 12 by a 32-bit value 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.
|
For professional programmers, details like these are sometimes important. But for most programs, use int
or long
for integers and double
for floating point. This will keep you out of trouble (usually). If you can't avoid the problem, use a type cast, as described in a future chapter.
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
?