Originally posted by sandeep bhatnagar:
hi friends,
this ques. is frm Khalid A. Mughal. book. we have given the following code which returns false when end of file(-1) comes. somebody plz explain it to me how it's happening. also tell me how it return true in other conditions.
public static boolean test(InputStream is) throws IOException {
int value=is.read();
return value == (value & 0xff);
}
thanx in advance
sandy
Hi Sandy,
From
Java API method read() of InputStream-
read
public abstract int read()
throws IOException
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
A subclass must provide an implementation of this method.
Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException - if an I/O error occurs.
Whenever a call to read() is successful it (actually its implementation in the subclass, as it's an abstract method) returns an int between 0 to 255, which is stored in the last byte of an int (last 8 LSBs), the first 3 bytes of the int in his case are 0.
(1) The code
(value & 0xff) gets last byte of the int variable "value" by masking it with a byte 0xff.
(2) Next, it is compared with the original integer "value" by the code
value == (value & 0xff), the byte gets promoted to an int having first 3 bytes as 0.
(3) For values in the range 0 to 255 of an int, the last byte is sufficient to cover the range, hence both the sides of the comparison/equality operator (==) are equal. Hence it returns true.
(4) For an EOF, the read() method's implementation returns -1, which is 0xffffffff for an int, when only last byte is masked (see 1), it evaluates to 0xff which is 255(0x000000ff). In this case
-1 is not equal to 255 hence it returns false.
HTH,
- Manish
[This message has been edited by Manish Hatwalne (edited October 24, 2001).]