Type Conversion&casting
Type Conversion&casting
For example, the following fragment casts an int to a byte. If the integer’s value
is larger than the range of a byte,
it will be reduced modulo (the remainder of an integer division by the) byte’s
range.
int a;
byte b;
b = (byte) a;
int a = 257;
byte b = (byte)a;
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.
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.
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.
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
Let’s look closely at the type promotions that occur in this line from the program: