I'm working through an example program provided in the Book "Java A Beginnner's Guide (9th Ed.)" by Herbert Schildt. The example reads:
The following program demonstrates
read()
by reading characters from the console until the user types a period.
The code looks like this:
import java.io.*;
public class ReadChars {
public static void main(String[] args) throws IOException{
char c;
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in, System.console().charset()));
System.out.println("Enter characters, period to quit.");
do {
c = (char) br.read();
System.out.println(c);
} while (c != '.');
}
}
The example output they provide looks like this:
Enter characters, period to quit.
One Two.
O
n
e
T
w
o
.
It to me suggests that the input was (as described) terminated at the '.'
character and then printed to the console.
However, when running the example myself, the output looks more like this:
Enter characters, period to quit.
abcde.fghij<return>
a
b
c
d
e
.
That is, I first have to terminate the input with <return>
and only then the characters are printed correctly up to the first '.'
character in the input.
I would like to understand what exactly is going on here. I assume it has something to do with the fact that the console input is somehow buffered and only flushed on <return>
, but to me this is a bit confusing given the structure of the code, which reads and prints the characters in a do-while loop and should break as soon as a '.'
is encountered.
Would someone be able to break down the order of things that are happening that lead to this behavior (i.e. the last output above) in contrast to the example output (i.e. the first output above)?