|
|
Operators and Assignments - Numeric Promotion
Unary Numeric Promotion
Binary Numeric Promotion
- when operands are of different types, automatic binary numeric promotion occurs with the smaller operand type being converted to the larger.
- the following rules are applied in the order given. (JLS §5.6.2)
- if either operand is a double, the other operand is converted to double
- otherwise, if one of the operands is a float, the other operand is converted to a float
- otherwise, if one of the operands is a long, the other operand is converted to a long
- otherwise, both operands are converted to int
Examples producing compile-errors:
byte = byte + byte; // found int, required byte
int = float + int; // found float, required int
long = float + long; // found float, required long
float = double + float; // found double, required float
Remember to check the type of the variable to which results are
assigned
Rules apply to following operators:
- Additive: + and -
- Multiplicative: *, /, and %
- Comparison: <, <=, >, and >=
- Equality: = and !=
- Bitwise: &, ^, and |
Special case for Ternary conditional operator (JLS §15.25)
- if one of the operands is byte and the other is short then the type of the expression is short
byte = true ? byte : short // found short, required byte
- if one of the operands is a constant of type int and the other operand has a type of byte, short, or char and the value of the int operand is within the other type range, the type of the expression will be the type of the non-int operand.
short = true ? short : 1000; // compiles and runs OK
short = false ? short : 1000; // compiles and runs OK
Example Code
Traps
- expression assigning byte or short operations to a byte or short variable
|