Let's look at each conversion. When the value 257 is cast into a byte variable, the result
is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case.
When the d is converted to an int, its fractional component is lost. When d is converted to
a byte, its fractional component is lost, and the value is reduced modulo 256, which in this
case is 67.
Automatic Type Promotion in Expressions
In addition to assignments, there is another place where certain type conversions may occur:
in expressions. To see why, consider the following. In an expression, the precision required
of an intermediate value will sometimes exceed the range of either operand. For example,
examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte, short,
or char operand to int when evaluating an expression. This means that the subexpression a * b
is performed using integers--not bytes. Thus, 2,000, the result of the intermediate expression,
50 * 40, is legal even though a and b are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors.
For example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable.
However, because the operands were automatically promoted to int when the expression was
evaluated, the result has also been promoted to int. Thus, the result of the expression is now
of type int, which cannot be assigned to a byte without the use of a cast. This is true even if,
as in this particular case, the value being assigned would still fit in the target type.
In cases where you understand the consequences of overflow, you should use an explicit
cast, such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows: First,
all byte, short, and char values are promoted to int, as just described. Then, if one operand
is a long, the whole expression is promoted to long. If one operand is a float, the entire
expression is promoted to float. If any of the operands is double, the result is double.
Search WWH :