Java Reference
In-Depth Information
Table 2.2
Converting between primitive data types.
int
long
float
double
char
byte
short
boolean
A
-
A
A
C
C
C
N
int
A
A
C
-
C
C
C
N
long
C
C
-
A
C
C
C
N
float
C
C
C
-
C
C
C
N
double
A
A
A
A
-
C
C
N
char
A
A
A
A
C
-
A
N
byte
A
A
A
A
C
C
-
N
short
N
N
N
N
N
N
N
-
boolean
Indicates that the least significant digits may be lost in the conversion even though the target type
allows for larger values. For example, a value in an int type that uses all 32 bits will lose some of
the lower bits when converted to a float since the exponent uses 8 of the 32 bits.
conversion is not allowed. Object types can also be involved in casts, but we
defer that discussion until Chapter 3.
When data of one primitive type is cast to another type, the effect on the
numerical values must be taken into account.
Narrowing conversions - When an integer type is cast to another integer type of a
smaller number n of bits, all but the n lowest-order bits are discarded. Depending on the
initial value, the result can have a different value and/or a different sign than the input
value.
Integer to floating-point conversions - These are widening conversions so explicit casts
are not required. However, note that the precision for large numbers can actually decrease
since the exponent occupies part of the four bytes allocated for a float and part of the
eight bytes for a double .Sothe mantissa decreases accordingly. A large int value
converted to a float can lose low-order bits and similarly for a long to a double .
2.10.2 Mixed types in expressions
If an expression holds a mix of types, the lower precision or narrower value
operand is converted to the higher precision or wider type. This result then must
be cast if it goes to a lower precision type:
double x, y = 3.0;
int j, i = 3;
x = i*y; //OKsince i is promoted to double
j = i*y; // Error since result is a double value
j = (int)(i * y) // OK because of the explicit cast
The process of converting a value to a wider or higher precision integer
or floating-point type is called “numeric promotion”. The Java language
specification states the following rules for promotion in an expression of two
Search WWH ::




Custom Search