Java Reference
In-Depth Information
the low 16 bits of these values, namely, 0x0000 and 0xffff ; it explains the char results,
which also are the low 16 bits of these values, namely, '\u0000' and '\uffff' ; and it ex-
plains the byte results, which are the low 8 bits of these values, namely, 0x00 and 0xff .
Despite the fact that overflow, underflow, or other loss of information may occur, a narrow-
ing primitive conversion never results in a run-time exception (§ 11.1.1 ) .
Example 5.1.3-2. Narrowing Primitive Conversions that lose information
Click here to view code image
class Test {
public static void main(String[] args) {
// A narrowing of int to short loses high bits:
System.out.println("(short)0x12345678==0x" +
Integer.toHexString((short)0x12345678));
// An int value too big for byte changes sign and magnitude:
System.out.println("(byte)255==" + (byte)255);
// A float value too big to fit gives largest int value:
System.out.println("(int)1e20f==" + (int)1e20f);
// A NaN converted to int yields zero:
System.out.println("(int)NaN==" + (int)Float.NaN);
// A double value too large for float yields infinity:
System.out.println("(float)-1e100==" + (float)-1e100);
// A double value too small for float underflows to zero:
System.out.println("(float)1e-50==" + (float)1e-50);
}
}
This program produces the output:
(short)0x12345678==0x5678
(byte)255==-1
(int)1e20f==2147483647
(int)NaN==0
(float)-1e100==-Infinity
(float)1e-50==0.0
5.1.4. Widening and Narrowing Primitive Conversion
The following conversion combines both widening and narrowing primitive conversions:
byte to char
First, the byte is converted to an int via widening primitive conversion (§ 5.1.2 ) , and then the
resulting int is converted to a char by narrowing primitive conversion (§ 5.1.3 ).
Search WWH ::




Custom Search