javawhile-loopbufferedreaderreadlineinputstreamreader

while loop with a readLine()


Here is my question: normal while loop looks like this -

while(condition){statements} 

and statements execute until condition becomes false and the loop is over. I'm interested in logic of this kind of statement:

while((a=b.readLine) != null) { ... } 

It's used in client - server communication in my case. The condition is sometimes true, sometimes isn't, but loop looks like it's testing the condition forever and when true, statements in {} execute. It looks to me that loop waits for the condition to be true and then runs statements. Is it somehow linked to the way BufferedReader and InputStreamReader work or what? Also, it seems this loop is never over, it just waits for a condition to be true and then runs statements, and then again waits for a condition to be true, etc. I would be thankful for any clarification.


Solution

  • while((a = b.readLine()) != null){ ... }
    

    At each iteration, the condition inside the parentheses is evaluated.

    Evaluating this expression consists in calling b.readLine(), affecting the returned value to a, and comparing a with null.

    Calling readLine(), as documented, consists in blocking until the next line is read. If there is no next line, readLine() returns null.

    So, in short, this while loop reads every line from the reader, does something with the line (inside the while block) and stops when the end of the stream is reached.