Reputation: 1078
Please explain the compiler behaviour in the below code snippet. Consider the text file contains the following text TOBE and the corresponding byte values are 84, 79, 66, 69
for(int i=0;i<4;i++){
byte inByte=(byte) buffInputFile.read();
system.out.println(inByte);
}
When i run this snippet i get the following output 84 79 66 69
But when i dubug at the for loop and step inside. The buffInputFile.read() shows me 84 at first and when assigned to inByte it is 79. and the output i get is
79,66,69,13 (13 is the carriage return).
Upvotes: 0
Views: 238
Reputation: 114837
That's not a bug, it's a feature. The read
method returns the next byte from the stream and sets the internal marker to the next position.
When you inspect buffInputFile.read()
with a debugger you effectively call that method and the debugger shows the actual value. But the marker has been set to the next position and so inByte
will receive the next value from the stream.
Upvotes: 1
Reputation: 1503839
I suspect you've got a debugger watch expression of buffInputFile.read()
- which is reading the value from the stream in order to display it... but that value then isn't available when the method is executed as part of the code. You've read that byte from the stream, so the next call to read()
will read the next byte, exactly as it's supposed to.
In general it's a very bad idea to execute methods with side effects within the debugger like this - it causes precisely this kind of confusion. If you just set a breakpoint on the line after the assignment, you can see the values that way.
In short: this isn't compiler behaviour going awry at all - it's the way you're using the debugger.
Upvotes: 3