When the buffer used by System.out.print
fills up, the output is written into the file (or terminal or other data target that is connected to the program's standard output stream), resulting in an empty buffer. Writing output without caring about the buffer size is normal usage. You will never crash or block your program or lose data from not calling flush
.
You only need to call flush
explicitly if you need to make the data available outside your program immediately. For example, if your program is exchanging data back and forth with another program, and you're sending a request to that program and will wait for that program's reply, you need to call flush
after sending your request to ensure that the other program receives it. Similarly, if your program (or the machine it runs on) crashes, only the output up to the last time you called flush
is guaranteed to have been written out.
If the stream is set to flush automatically, then writing a newline character (explicitly or through println
) is as good as calling flush
. Calling close
also calls flush
(that's why close
can throw an IOException
: it might have to write data out and not be able to, e.g. because the stream is connected to a file on a full disk).
Note that flushing the buffer may cause the program to block, if the stream that System.out
is connected to is not immediately ready to receive the data (e.g. when the data is piped to another program that doesn't read its input immediately). Since the buffer can be flushed at any time (because the buffer happens to be full), any call to print
with a non-empty argument is potentially blocking.
For more information, see the buffered streams tutorial and the documentation of the java.io.PrintStream
class.
System.setOut()
to replaceSystem.out
with a custom stream that throws an exception – Mcdaniels\n
has nothing to do with it, calling.close()
or.flush()
has everything to do with contents of a stream being written out or being lost. – Manuelmanuela