Java Reference
In-Depth Information
short numOranges = 5;
short numApples = 10;
short numFruit = 0;
then the program will no longer compile. The problem is with the statement:
numFruit = numOranges + numApples;
Since the expression numOranges + numApples produces a 32-bit result, the compiler cannot store
this value in numFruit , as the variable numFruit is only 16-bits long. You must modify the code to
convert the result of the addition back to a 16-bit number. You do this by changing the statement to:
numFruit = (short)(numOranges + numApples);
The statement now calculates the sum of numOranges and numApples and then converts or casts it to
the type short before storing it in numFruit . This is called an explicit cast, and the conversion
process is referred to as casting. The cast to type short is the expression (short) , and the cast applies
to whatever is immediately to the right of (short) so the parentheses around the expression
numOranges + numApples are necessary. Without them the cast would only apply to the variable
numOranges , which is a short anyway, and the code would still not compile. Similarly, if the
variables here were of type byte , you would need to cast the result of the addition to the type byte .
The effect of the cast to short is just to take the least significant 16 bits of the result, discarding the most
significant 16 bits. The least significant bits are those at the right hand end of the number because the
bits in a binary number in Java increase in value from right to left. Thus the most significant bits are
those at the left hand end. For the cast to type byte only the least significant 8 bits are kept. This means
that if the magnitude of the result is such that more than 16 bits are necessary to represent it (or 8 bits in
the case of a cast to byte ), your answer will be wrong. You will get no indication from the compiler
that this has occurred because it was you, after all, that expressly specified the cast and the compiler
assumes that you know what you are doing. You should therefore avoid explicit casts in your programs
unless they are absolutely essential.
An integer arithmetic operation involving a value of type long will always be carried using 64-bit
values. If the other number in such an operation is not of type long , it will be cast to long before the
operation is executed. For example:
long result = 0;
long factor = 10L;
int number = 5;
result = factor*number;
To execute the last statement, because the variable, factor , is of type long , the multiplication will be
carried out using long values. The value stored in the variable, number , will be converted to type
long , and that will be multiplied by the value of factor .
All other integer arithmetic operations involving types other than long are carried out with 32-bit
values. Thus, you only really need to consider two kinds of integer literals:
Search WWH ::




Custom Search