Java Reference
In-Depth Information
by the compiler. Now you can see why Java didn't give any errors for this expression. Because the
int
literal
5
is in the
range of
-128
to
127
,
b1 = 5
is a valid assignment according to the rule of assignment of
int
literal to a
byte
variable.
However, if you try to write an expression as
b1 = 127 + 10
, certainly it would not compile because the result of
127 + 10
is
137
and is thus out of range for a
byte
data type.
Here are the final words on the data type conversion of the operands and the determination of the type of the
expression involving the addition operator.
var = operand1 + operand2;
If
operand1
and
operand2
are compile-time constants, the result of
operand1 + operand2
determines whether
the above assignment is valid. If the result of
operand1 + operand2
is in the range for the data type of the variable
var
,
the above expression will compile. Otherwise, a compile-time error is generated. If either
operand1
or
operand2
is a
variable (that is, the value of either
operand1
or
operand2
cannot be ascertained at compile time), the data type of the
expression is determined according to one of the four rules discussed in the beginning of this section. The following
are examples of correct and incorrect use of the addition operator. The comments along with the code indicate
whether the user is correct.
byte b1 = 2;
byte b2 = 3;
short s1 = 100;
int i = 10;
int j = 12;
float f1 = 2.5F;
double d1 = 20.0;
b1 = 15 + 110; // Ok. 125 is in the range -128 and 127
// An error. i is promoted to int and i + 5 is of the data type int.
// int to byte assignment is not permitted
b1 = i + 5;
b1 = (byte)(i + 5); // OK
// An error. s1 is promoted to int and s1 + 2 is of the data type int.
// int to byte assignment is not permitted
b1 = s1 + 2;
// An error. b2 is promoted to float and f1 + b2 is of the data type float.
// float to byte assignment is not permitted
b1 = f1 + b2;
// An error. f1 is promoted to double and f1 + d1 is of the data type double
b1 = f1 + d1;
// Ok. i is promoted to float and i + f1 is of the data type float
f1 = i + f1;
// An error. i is promoted to double and i + d1 is of data type double.
// double to float assignment is not permitted
f1 = i + d1;
f1 = (float)(i + d1); // OK