The problem is that the object System.out
is of type PrintStream
which uses in its implementation an instance of BufferedOutputStream
to perform the scripts.
The BufferedOutputStream
do not perform a physical write each time you invoke any of its methods write()
, but, it will store the data that you have been sent to write until an internal buffer is filled and it is then when the physical writing of the data. The objective of this mechanism is to optimize the processes of physical writes (for example in a hard disk) since these are very expensive. If we write the data byte by byte, our program takes longer to write the data itself than in its internal functioning.
There is a way to force physical writes, and it is using the flush()
method, which forces you to write the contents of the internal buffer.
If you read the documentation for the method System.out.write(int)
you can see that only the flush()
method will be called if the character that represents the parameter is a line break
If the byte is a newline and automatic flushing is enabled then the flush method will be invoked.
For all the above is that the character is not written in the console, because it remains in the internal buffer of the object System.out
and upon completion of the execution of the program this data is lost.
To correct the problem, just add a flame to flush()
try {
int n = System.in.read();
System.out.write(n);
System.out.flush();
} catch (IOException e) {
e.printStackTrace();
}
or print a line break
try {
int n = System.in.read();
System.out.write(n);
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
or, use the print()
or println()
method instead of write()
. That if, to use any of these you must cast your whole to char
try {
int n = System.in.read();
System.out.print((char) n);
} catch (IOException e) {
e.printStackTrace();
}
I hope you have explained as clearly as possible and that you have understood it.