23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

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.

<strong>Java</strong> I/O<br />

data types in <strong>Java</strong>, a byte is signed. The maximum byte value is 127. 128, 129, and so on<br />

through 255 are not legal values for bytes.<br />

There are no short or byte literals in <strong>Java</strong>. When you write the literal 42 or 24000, the<br />

compiler always reads it as an int, never as a byte or a short, even when used in the righthand<br />

side of an assignment statement to a byte or short, like this:<br />

byte b = 42;<br />

short s = 24000;<br />

However, in these lines a special assignment conversion is performed by the compiler,<br />

effectively casting the int literals to the narrower types. Because the int literals are constants<br />

known at compile time, this is permitted. However, assignments from int variables to shorts<br />

and bytes are not, at least not without an explicit cast. For example, consider these lines:<br />

int i = 42;<br />

short s = i;<br />

byte b = i;<br />

Compiling these lines produces the following errors:<br />

Error: Incompatible type for declaration.<br />

Explicit cast needed to convert int to short.<br />

ByteTest.java line 6<br />

Error: Incompatible type for declaration.<br />

Explicit cast needed to convert int to byte.<br />

ByteTest.java line 7<br />

Note that this occurs even though the compiler is theoretically capable of determining that the<br />

assignment does not lose information. To correct this, you must use explicit casts, like this:<br />

int i = 42;<br />

short s = (short) i;<br />

byte b = (byte) i;<br />

Even simple arithmetic with small, byte-valued constants as follows produces "Explicit cast<br />

needed to convert int to byte" errors:<br />

byte b = 1 + 2;<br />

In fact, even the addition of two byte variables produces an integer result and thus cannot be<br />

assigned to a byte variable without a cast; the following code produces that same error:<br />

byte b1 = 22;<br />

byte b2 = 23;<br />

byte b3 = b1 + b2;<br />

For these reasons, working directly with byte variables is inconvenient at best. Many of the<br />

methods in the stream classes are documented as reading or writing bytes. However, what<br />

they really return or accept as arguments are ints in the range of an unsigned byte (0-255).<br />

This does not match any <strong>Java</strong> primitive data type. These ints are then converted into bytes<br />

internally.<br />

18

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

Saved successfully!

Ooh no, something went wrong!