First, what exactly the StringReader.ready() do?
The general contract is that returns true if the next read won't block. In the case of StringReader
that is always true.
Can I use it as a condition in a while loop so that the loop terminates when the string ends? Reading the java doc didn't help much (or maybe I misunderstood what they meant by "Returns True if the next read() is guaranteed not to block for input")
No. A simple test reveals that. You should loop until read()
returns -1. Note that you must store the result of read()
into an int
for this to work.
In the while loop that I have constructed, the method StringReader.read() somehow returns -1.
No 'somehow' about it. That's what it's supposed to do.
What does this mean?
It means end of stream. In this case, you've read all the characters out of the StringReader.
Again, the Java doc did not help.
On the contrary. The Javadoc clearly states that read()
returns "the character read, or -1 if the end of the stream has been reached".
I am guessing that it means that the string has already terminated
No need to guess about it. That's explicitly what the Javadoc says.
but then that means the ready() method is not doing what it is supposed to do!
No it doesn't. The Javadoc doesn't say that ready()
returns false
at end of stream. You don't have any warrant for that statement. In this case, it returned true, you called read()
, and it didn't block. Contract satisfied.