So a data type with lower precision (fewer bits) can be converted
to a type of higher precision without explicit casting. To convert
a higher precision type to a lower precision, however, an explicit
cast is required or the compiler will flag an error.
Note that when you cast a value of a wider type down to a more
narrow type, such as an int
value to a byte
variable, the upper bytes will be truncated. That is, the lowest
order byte in the int
value will be copied to the byte
value.
Primitive
Type Conversion Table
Below is a table that indicates to which of the other primitive
types you can cast a given primitive data type. The symbol C
indicates that an explicit cast is required since the precision
is decreasing. The symbol A indicates that the precision
is increasing so an automatic cast occurs without the need for
an explicit cast. N indicates that the conversion is not
allowed.
|
int |
long |
float |
double |
char |
byte |
short |
boolean |
int |
- |
A |
A* |
A |
C |
C |
C |
N |
long |
C |
- |
A* |
A* |
C |
C |
C |
N |
float |
C |
C |
- |
A |
C |
C |
C |
N |
double |
C |
C |
C |
- |
C |
C |
C |
N |
char |
A |
A |
A |
A |
- |
C |
C |
N |
byte |
A |
A |
A |
A |
C |
- |
A |
N |
short |
A |
A |
A |
A |
C |
C |
- |
N |
boolean |
N |
N |
N |
N |
N |
N |
N |
- |
The * asterisk indicates that the least significant digits
may be lost in the conversion even though the target type allows
for bigger numbers. For example, a large value in an int
type value that uses all 32 bits will lose some of the lower bits
when converted to float
since the exponent uses 8 bits of the 32 provided for float
values.
Mixed Types in an Expression
If an expression holds a mix of types, the lower precision
or narrower value operand is converted to a higher precision
or wider type. This result then must be cast if it goes to a
lower precision type:
float
x,y=3;
int j,i=3;
x=
i*y; // OK since i will
be promoted to float
j= i*y; //
Error
since result is a float value
j= (int)(i*y) // OK
The process of converting a value to a wider or higher precision
integer or floating point type is called "numeric promotion".
The Java VM specification states the following rules for promotion
in an expression of two operands, as in x+i:
-
If either operand is of type double,
the other is converted to double.
-
Otherwise, if either operand is of type float,
the other is converted to float.
-
Otherwise, if either operand is of type long,
the other is converted to long.
-
Otherwise, both operands are converted to
type int.
Chapter 2: Tech
section adds more discussion about
casting.
Latest update: Oct. 14, 2004