I have a block of uncommented code I’m trying to understand. The comments are my own.
//create an array name header that holds 4 bytes
byte header[] = new byte[4];
int len = 0;
int c = -1;
for(; len != 3; len += c)// run loop till len = 3
{
try
{
//first run of the loop following should be true
//read 3 bytes and save into header array starting at 0
// c = number of bytes read (most likely 3 after first run of loop)
c = is.read(header, len, 3 - len);
}
catch(Exception e)
{
System.err.println("read header error " + e.getMessage());
displayErrorMessage(e);
}
if(c == -1)
return null;
}
This code is reading an input stream but I’m not sure how many times it will loop.
I tried running through the loop on paper, replacing len and c each time and after 7 iterations len still did not equal 3.
During second run of the loop, len should equal -1 and c should equal 3. The -1 should make the read method throw an IndexOutOfBoundsException because you are trying to save the byte read from the stream to header[-1]. So since an exception is thrown, the value of c would remain equal to 3 from first run of the loop.
Am I right in assuming that since the exception is caught, the for loop does not exit?
The number of times the loop will be repeated is not deterministic, since
read()might read 3 bytes at the first run, and terminate – or it might read 1 byte at a time, and repeat 3 times.However, as the comment says – it is very likely that
read()will read during the first iteration 3 bytes and the loop will have only one iteration.For this case what happen is the following:
len < 3– it isc = 3c == -1– it is notlen = len + c = 3len < 3– it is not: terminate the loop