Eric Liu Eric Liu - 1 month ago 14
Java Question

Assignment in a boolean expression of a while loop

I got this question from Head First Java by Kathy Sierra and Bert Bates. In the Networking and Threads section of the book, they built a chat client and handled incoming messages by starting a separate thread:

public class IncomingReader implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) { //reader is a BufferedReader from an InputStreamReader of a Socket
System.out.println("read " + message);
incoming.append(message + "\n"); //incoming is a JTextArea they declared earlier
}
} catch (Exception ex) {ex.printStackTrace();}
}}


And this thread is started only once, after they setup the Swing GUI and the readers and writers.

So my question is, how is this thread able to stay alive and keep listening for incoming messages. Shouldn't it go past the while loop and die when
message
is
null
?

Answer

BufferedReader will keep on reading the input until it reaches the end. But if there is nothing to read, then it will keep looping or wait until there is input.

BufferedReader readLine() blocks

Comments