From the PrintStream documentation:
Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.
Then given code
System.out.print("hi"); // gives console output: hi
System.out.print(7); // gives console output: 7
// prevents flushing when stream wiil be closed at app shutdown
for (;;) {
}
Why then I see output to my console? Nothing shall be written to console (PrintStream instance from System.out), because nothing shall be flushed so far!
This didn't answer this.
I guess, the answer is in the source code (private utility method BufferedWriter.flushBuffer()), but I don't understand the comment to code: "Flushes the output buffer to the underlying character stream, without flushing the stream itself": if PrintStream (which is tied to console output), which is "stream itself" is not flushed, output to console shall not be refreshed!...
Source for PrintStream.print(String):
private void write(String s) {
try {
synchronized (this) {
ensureOpen();
textOut.write(s);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush && (s.indexOf('\n') >= 0))
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
Source for BufferedWriter.flushBuffer():
/**
* Flushes the output buffer to the underlying character stream, without
* flushing the stream itself. This method is non-private only so that it
* may be invoked by PrintStream.
*/
void flushBuffer() throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar == 0)
return;
out.write(cb, 0, nextChar);
nextChar = 0;
}
}
More details are also given here. It is very complicated, but seems like at some stage BufferedWriter is given to PrintStream constructor.
I went step by step using debugger and this is what I found:
String sis displayed in the console after 527th line, so it's before line 528 in which the check of having\nis done.In
charOut.flushBuffer()deep inside, there is the following method called:In which, the check about
\nis missing.The flow is as it follows:
System.out#print(String s)callsPrintStream#print(String s).PrintStream#print(String s)callsPrintStream#write(String s).PrintStream#write(String s)callsOutputSteamWriter#flushBuffer().OutputStreamWriter#flushBuffer()callsStreamEncoder#flushBuffer().StreamEncoder#flushBuffer()callsStreamEncoder#implFlushBuffer().StreamEncoder#implFlushBuffer()callsStreamEncoder#writeBytes().StreamEncoder#writeBytes()callsPrintStream#write(byte buf[], int off, int len)which flushes the bufforif(autoFlush).The most important snippets are above. The
BufferedWriterseems not to be called in this flow.