10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5.1.4 Widening and Narrowing Primitive Conversions CONVERSIONS AND PROMOTIONS<br />

84<br />

0x0000 and 0xffff; it explains the char results, which also are the low 16 bits of<br />

these values, namely, '\u0000' and '\uffff'; and it explains the byte results,<br />

which are the low 8 bits of these values, namely, 0x00 and 0xff.<br />

Despite the fact that overflow, underflow, or other loss of information may<br />

occur, narrowing conversions among primitive types never result in a run-time<br />

exception (§11).<br />

Here is a small test program that demonstrates a number of narrowing conversions<br />

that lose information:<br />

class Test {<br />

public static void main(String[] args) {<br />

// A narrowing of int to short loses high bits:<br />

System.out.println("(short)0x12345678==0x" +<br />

Integer.toHexString((short)0x12345678));<br />

// A int value not fitting in byte changes sign and magnitude:<br />

System.out.println("(byte)255==" + (byte)255);<br />

// A float value too big to fit gives largest int value:<br />

System.out.println("(int)1e20f==" + (int)1e20f);<br />

// A NaN converted to int yields zero:<br />

System.out.println("(int)NaN==" + (int)Float.NaN);<br />

// A double value too large for float yields infinity:<br />

System.out.println("(float)-1e100==" + (float)-1e100);<br />

// A double value too small for float underflows to zero:<br />

System.out.println("(float)1e-50==" + (float)1e-50);<br />

}<br />

}<br />

This test program produces the following output:<br />

(short)0x12345678==0x5678<br />

(byte)255==-1<br />

(int)1e20f==2147483647<br />

(int)NaN==0<br />

(float)-1e100==-Infinity<br />

(float)1e-50==0.0<br />

DRAFT<br />

5.1.4 Widening and Narrowing Primitive Conversions<br />

<strong>The</strong> following conversion combines both widening and narrowing primitive convesions:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!