This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Howdy! Greetings to all reading my post. I've been reviewing with much effort the exercises in the Head First Book, and I have encountered a little piece of code I don't Understand, it's in the Simple Chat Client exercise that's on page(s) 518 - 519.
Inside the IncomingReader inner class there is a while loop that I would like to have explained to me by someone who has seen it and understood it.
What I don't understand about it is:
Why is it a Loop that loops forever?
And How does the condition inside the while loop make the program wait for something to be read and repeat again without exiting?
Please help me with this one friends. I really need to understand this exercise to move forward.
As you can see, this does not necessarily loop forever. Once there is nothing more to read, reader.readLine() returns null and the loop ends.
As for the waiting, all classes in the java.io package use blocking reads. When the method is called and enough data is available, it returns immediately. If there isn't though, the method blocks until enough data becomes available. In your case, the program waits until a full line can be read. This is then returned, processed, and waits until another full line can be read. If all lines have been read (usually because the source has closed) the readLine() method does not block anymore but returns null, and the loop exits.
A while loop executes the condition (the stuff inside the parentheses.) If it evaluates to "true", then the loop executes the body (the stuff in the brackets.) After that, it repeats by evaluating the condition again, and if the condition is "true", it executes the body again... until the condition evaluates to false.
In this loop, the condition is
(message = reader.readLine()) != null
this is a tricky expression because it has a side effect: it sets the value of a variable. Here's how Java evaluates this condition:
1) It calls the method reader.readLine(), which returns the next line of text from the socket. If the socket is still open, but there's nothing to read, it will just wait; it won't return until something shows up, or until the socket closes.
2) It assigns the value returned by the method to the variable "message".
3) It compares that same method-call result to "null". If it is null, there's no more data, and the value of the whole condition is "false". If it's not null, the condition is true, so we process the line and read another one.
It does make perfect sense. I understand it now. I knew there was more to it inside the expression evaluated by the while loop. I wonder why there wasn't a further explanation about it somewhere in the book...
If you have any other comments on the subject please let me know. Thanks for clarifying my doubts. I appreciate it a lot.