Try this code -
import java.io.StringReader;
public class StringReaderTest
{
public static void main(String[] args) throws Exception
{
String sampleString = "abcdefg";
StringReader reader = new StringReader(sampleString);
for(int i=0; i<40; i++)
{
char c = (char) reader.read();
System.out.print(c);
}
}
}
The output is -
abcdefg?????????????????????????????????
So the reader actually read past the end of the input. I was under the impression that it should have thrown an exception when it tried to read beyond "g", but it did not. It instead returned a "?" character. Is this a bug or is this expected behavior?
The documentation is quite clear in this case:
StringReader.read()
Returns: The character read, or -1 if the end of the stream has been reached