System.out is based around a PrintStream which by default flushes whenever a newline is written.

From the javadoc:

autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written

So the println case you mention is explicitly handled, and the write case with a byte[] is also guaranteed to flush because it falls under "whenever a byte array is written".

If you replace System.out using System.setOut and don't use an autoflushing stream, then you will have to flush it like any other stream.

Library code probably shouldn't be using System.out directly, but if it does, then it should be careful to flush because a library user might override System.out to use a non flushing stream.

Any Java program that writes binary output to System.out should be careful to flush before exit because binary output often does not include a trailing newline.

Answer from Mike Samuel on Stack Overflow
🌐
Coderanch
coderanch.com › t › 274783 › java › flush
what happens in out.flush()? (I/O and Streams forum at Coderanch)
From your example it looks like System.out is not buffered, so characters are being sent as soon as they enter the stream. If you were to wrap System.out in a BufferedWriter, you might see a greater difference when you call "flush()". For example: ... Dear Frank Carver, thanks a lot for cleared the doubt. also i have changed the name according to the norms by javaranch.
Discussions

java - why we use system.out.flush()? - Stack Overflow
Can someone please explain why we we would use system.out.flush() in a simpler way? If there could be a chance of losing data, please provide me with an example. If you comment it in the code below More on stackoverflow.com
🌐 stackoverflow.com
October 4, 2013
System.out.flush()
It causes everything that's been written to System.out to be completely written. System.out can do some internal buffering of data, so you aren't guaranteed that something written to the stream will appear immediately in the standard output of the process... unless you call flush(). More on thecodingforums.com
🌐 thecodingforums.com
1
September 26, 2004
Help with Java.io.PrintWriter.flush()? Also a bit of a rant.
The meaning of "flush" is pretty consistent through the entire IO framework, and it isn't specific to the PrintWriter class. You can find good documentation in the base Writer class , for example: Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams. If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive. For example, if you are writing to a file, it is inefficient to write every single byte individually to the file; it is more efficient to write larger chunks to the file. Therefore, the FileWriter implementation might store your written bytes in some kind of buffer (such as a byte array) until it has a sufficiently large chunk to write to the file, so that it can be done efficiently. By invoking the flush() method, you can explicitly "flush" the buffer, which basically means that it take all of the bytes stored in the buffer and write them to the file/destination immediately, and clear/reset the buffer. Typically, you don't need to worry about explicitly calling flush(), as it will be done automatically when you close the writer or outputstream. More on reddit.com
🌐 r/learnjava
6
0
October 19, 2020
java - System.out not flushing - Stack Overflow
I have a java application that takes input via a Scanner reading System.in, and gives output via System.out. The scanner is always active, it does not terminate without using Ctrl+C via the termina... More on stackoverflow.com
🌐 stackoverflow.com
December 6, 2016
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
When to Call System.out.flush() in Java - Java Code Geeks
January 10, 2024 - This improves the user experience, ... the System.out.flush() method emerges as a valuable tool for managing output streams, ensuring efficient and timely information presentation....
🌐
Baeldung
baeldung.com › home › java › core java › when to call system.out.flush() in java?
When to Call System.out.flush() in Java? | Baeldung
January 8, 2024 - Java provides a built-in mechanism to explicitly flush output streams, namely the flush() method. This method is part of the OutputStream class and its subclasses, including the type behind System.out.
🌐
Tutorialspoint
tutorialspoint.com › java › io › console_flush.htm
Java - Console flush() method
The following example shows the usage of Java Console flush() method. package com.tutorialspoint; import java.io.Console; public class ConsoleDemo { public static void main(String[] args) { Console console = null; try { //Create a console object. console = System.console(); // test for console not null if (console != null) { // read line from the console String name = console.readLine("Enter name : "); // print System.out.println("You have entered : " + name); } // flushes console and forces output to be written console.flush(); } catch(Exception ex) { // if any error occurs ex.printStackTrace(); } } } Let us compile and run the above program, this will produce the following result − ·
🌐
Google Groups
groups.google.com › g › comp.lang.java.help › c › bPPPDljqviY
System.out PrintWriter print() and flush() not flushing?
> > >catch ( SocketTimeoutException ste ) > > { > > //doesn't flush > > System.out.print("."); > > System.out.flush(); > > doNewline = true; > > } > > That should work. > > what evidence do you have this code is ever executed? > what happens with System.err.println("timed out"); > -- > > Roedy Green Canadian Mind Products > The Java Glossaryhttp://mindprod.com ·
🌐
Tabnine
tabnine.com › home page › code › java › java.io.printstream
java.io.PrintStream.flush java code examples | Tabnine
*/ public static String stackTraceToString(Throwable cause) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(out); cause.printStackTrace(pout); pout.flush(); try { return new String(out.toByteArray()); } finally { try { out.close(); } catch (IOException ignore) { // ignore as should never happen } } } ... private static void sendRequest(OkHttpClient client, String url) { System.out.printf("%-40s ", url); System.out.flush(); System.out.println(Platform.get()); Request request = new Request.Builder().url(url).build(); try (Response response = client.n
Find elsewhere
🌐
YouTube
youtube.com › watch
Java Flushing Output with the Flush Method - Send Buffer to Output Stream - APPFICIAL - YouTube
A buffer is a portion in memory that is used to store a stream of data (characters). These characters sometimes will only get sent to an output device (e.g. ...
Published   April 27, 2018
🌐
Sololearn
sololearn.com › en › Discuss › 1141033 › what-is-system-out-flush
What is System. out. Flush() ; | Sololearn: Learn to code for FREE!
March 13, 2018 - javacode · 13th Mar 2018, 10:08 ... program performance. Flush is used to tell the i/o system you don't care about performance you want to be sure the data is guaranteed to be written now....
🌐
GeeksforGeeks
geeksforgeeks.org › java › printwriter-flush-method-in-java-with-examples
PrintWriter flush() method in Java with Examples - GeeksforGeeks
October 24, 2025 - Calling flush() ensures that it appears on the console immediately. Example 2: Writing a Character to Console · Java · import java.io.PrintWriter; class GFG{ public static void main(String[] args){ try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Write a character to the stream writer.write(65); // ASCII value of 'A' // Flush the stream to ensure immediate output writer.flush(); } catch (Exception e) { System.out.println(e); } } } Output ·
🌐
Tutorialspoint
tutorialspoint.com › java › io › outputstream_flush.htm
Java - OutputStream flush() method
The Java OutputStream flush() method flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the
🌐
Narkive
programming.comp.narkive.com › oXFeph2J › use-of-system-out-flush-in-java
use of system.out.flush() in java?
Of course. It causes everything that's been written to System.out to be completely written. System.out can do some internal buffering of data, so you aren't guaranteed that something written to the stream will appear immediately in the standard output of the process... unless you call flush().
🌐
The Coding Forums
thecodingforums.com › archive › archive › java
System.out.flush() | Java | Coding Forums
September 26, 2004 - It causes everything that's been written to System.out to be completely written. System.out can do some internal buffering of data, so you aren't guaranteed that something written to the stream will appear immediately in the standard output of the process... unless you call flush().
🌐
GeeksforGeeks
geeksforgeeks.org › java › console-flush-method-in-java-with-examples
Console flush() method in Java with Examples - GeeksforGeeks
June 12, 2020 - // Java program to illustrate // Console flush() method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( "No console available"); return; } String str = cnsl.readLine( "Enter string : "); System.out.println( "You entered : " + str); // Revoke flush() method cnsl.flush(); } }
🌐
O'Reilly
oreilly.com › library › view › java-i-o › 1565924851 › ch02s04.html
Flushing and Closing Output Streams - Java I/O [Book]
March 16, 1999 - For example, again assuming out is an OutputStream of some sort, calling out.close() closes the stream and implicitly flushes it. Once you have closed an output stream, you can no longer write to it. Attempting to do so will throw an IOException. Again, System.out is a partial exception because as a PrintStream , all exceptions it throws are eaten.
Author   Elliotte Rusty Harold
Published   1999
Pages   600
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-mastering-java-system-out-flush
Mastering Java System Out Flush: A Comprehensive Guide - CodingTechRoom
This means it's not sent immediately to the console. Flushing controls this behavior directly, allowing you to send data to the output device promptly when needed. ... Solution: Use `System.out.flush()` after frequent outputs or before program termination to ensure all data is printed.
🌐
CodingTechRoom
codingtechroom.com › question › understanding-system-out-flush-in-java-when-and-why-to-use-it
When and Why Should You Call System.out.flush() in Java? - CodingTechRoom
For instance, if you create a `PrintWriter` using a `OutputStream`, setting the auto-flush flag means that the stream will automatically flush whenever a newline character is written. However, System.out is not necessarily set to auto-flush, thus the requirement to call flush in some scenarios.
🌐
Reddit
reddit.com › r/learnjava › help with java.io.printwriter.flush()? also a bit of a rant.
r/learnjava on Reddit: Help with Java.io.PrintWriter.flush()? Also a bit of a rant.
October 19, 2020 -

So I am confused with the flush() method of the PrintWriter class. According to all documentation descriptions, it 'flushes' the stream, whatever that means. Luckily I got a better explanation somewhere else, but even then it didn't explain how I'd seen it function. GeeksforGeeks said " it means to clear the stream of any element that may be or maybe not inside the stream". Ok, so I assume that just means it empties the stream, yes?

No, that is not what it does. The given code from the GeeksforGeeks website (found here) is as follows:

// Java program to demonstrate 
// PrintWriter flush() method 
  
import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // The string to be written in the Writer 
        String str = "GeeksForGeeks"; 
  
        try { 
  
            // Create a PrintWriter instance 
            PrintWriter writer 
                = new PrintWriter(System.out); 
  
            // Write the above string to this writer 
            // This will put the string in the stream 
            // till it is printed on the console 
            writer.write(str); 
  
            // Now clear the stream 
            // using flush() method 
            writer.flush(); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
} 

With output as follows:

GeeksForGeeks

Simple enough right? Well if you remove line 26 of the code above (writer.flush()) then you get no output. So that means that when you flush the input stream, it actually goes somewhere, it doesn't just get erased. So why isn't that put into the documentation and explanation?

I am upset about this whole thing and I'm annoyed that the official documentation doesn't elaborate more on what 'flush' means in the context of the method, class, etc. But aside from me being upset, I would like someone to either explain whats going on here or to link me to some documentation that actually gets it right.

Top answer
1 of 4
4
The meaning of "flush" is pretty consistent through the entire IO framework, and it isn't specific to the PrintWriter class. You can find good documentation in the base Writer class , for example: Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams. If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive. For example, if you are writing to a file, it is inefficient to write every single byte individually to the file; it is more efficient to write larger chunks to the file. Therefore, the FileWriter implementation might store your written bytes in some kind of buffer (such as a byte array) until it has a sufficiently large chunk to write to the file, so that it can be done efficiently. By invoking the flush() method, you can explicitly "flush" the buffer, which basically means that it take all of the bytes stored in the buffer and write them to the file/destination immediately, and clear/reset the buffer. Typically, you don't need to worry about explicitly calling flush(), as it will be done automatically when you close the writer or outputstream.
2 of 4
1
Other answers have addressed the buffer flushing so I'll comment on the example code. That implementation's leaky; doesn't directly close the writer and certainly doesn't do it in a finally block. It should use "try with resources" like this try (PrintWriter writer = new PrintWriter(System.out) { ... } https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Top answer
1 of 3
2

This sounds a lot like the output isn't being flushed, as its only System.out.print that has the trouble.

Typically System.out and System.err are configured differently. (System.err is typically not buffered, and System.out is typically buffered.) However, the javadocs do not specify the flushing behavior of either streams. This could explain the differences in behavior between the (real) console and running in an IDE.

For info, here is how the streams are initialized in Java 8:

    FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
    FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
    FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
    setIn0(new BufferedInputStream(fdIn));
    setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
    setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));

private static PrintStream  ewPrintStream(FileOutputStream fos, String enc) {
   if (enc != null) {
        try {
            return new PrintStream(new BufferedOutputStream(fos, 128),
                                   true, enc);
        } catch (UnsupportedEncodingException uee) {}
    }
    return new PrintStream(new BufferedOutputStream(fos, 128), true);
}

As you can see, System.out is initialized as buffered with autoflush enabled.


However, adding System.out.flush() after the print statement does not cause it to print.

Are you sure about that? A flush() should flush any buffered output.

I suggest that the problem is actually somewhere else; e.g. the print or flush calls are not happening ... for some reason.


It is also possible that some of your problems are due to this:

System.out.print(",\\" + '\n');

As @javaguy points out, a newline character is a platform specific line separator. On some platforms, the console requires something different. The simplest platform independent way to tell the console to do a line break is:

System.out.println(",\\");

Or putting it all together:

System.out.println(",\\");
System.out.print("     " + someString); 
System.out.flush();   // This is necessary ... and should work.
2 of 3
0

Assuming that you are running the program in Windows, the carriage return (\r) and line feed (\n) together need to be added to print the new line as below:

System.out.print(",\\" + '\r\n');
System.out.print("     " + someString);