Java Reference
In-Depth Information
use the cast operator. The compiler complains about a possible loss of precision, but casting
fi xes the problem:
short s1 = 10, s2 = 12;
short sum = (short) (s1 + s2);
The value of sum is 22 after this code executes.
A Note about Casting
I want to take a moment to point out something subtle but important about the cast oper-
ator. The sole purpose of casting primitive types is to make the compiler happy. When
you assign a larger data type to a smaller one, the compiler complains about a possible
loss of precision.
However, if you are aware and comfortable with the possible loss of precision at runtime,
then you simply cast the result, which tells the compiler you know what you are doing. At
runtime, the data may very well be invalid. For example, the following code compiles and
runs, but you might be surprised by the output:
byte b1 = 60, b2 = 60;
byte product = (byte) (b1 * b2);
System.out.println(product);
This code outputs the number 16, clearly not the result of 60 times 60. The mistake lies in
the limitations of a byte , which can only store values up to 127. Because 60 * 60 = 3600,
the value of 16 is the lower 8 bits of the binary representation of 3600. The signifi cant bits
were lost in the runtime assignment of 3600 to the byte product.
We will revisit this discussion of casting again when we talk about inheritance and cast-
ing references in Chapter 6, “OO Concepts,” because casting reference types is a differ-
ent story altogether!
The JVM ensures order of operations is evaluated left-to-right when operators share the
same precedence. For example, what is the value of x after this line of code executes?
String x = 12 - 6 + “Hello” + 7 + 5;
Following the order from left to right, 12 - 6 is evaluated fi rst and results in 6. The
next + operator is not addition but string concatenation, so the 6 is promoted to a String
and the result is “6Hello” . Following left to right, the next + is also string concatenation,
resulting in “6Hello7” , and fi nally the value of x after the last string concatenation is
“6Hello75” .
Search WWH ::




Custom Search