Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does System.out.write method flush the stream?

Tags:

java

public class Test {
 public static void main(String..args) {
    System.out.println("Testing.");
    System.out.print("Testing Again.");
    }
  }

Hello i'm new in java and i reading it from Herbert Schildt Book. So my first Question.

  1. I want to know in above program that does print() method flushes the stream As println() flushes after a newline at end.
  2. Does System.out.write(); Method flushes the stream?. Please be Specific.
like image 683
Muhammad Yasir Avatar asked Jun 14 '26 03:06

Muhammad Yasir


1 Answers

Yes, both System.out.print and System.out.write also flush the stream.

(edit: it seems the stream is only flushed if the input string contains a newline).

If you look at the source code for PrintStream.java from java.io, you can see the source:

private void write(char buf[]) {
    try {
        synchronized (this) {
            ensureOpen();
            textOut.write(buf);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush) {
                for (int i = 0; i < buf.length; i++)
                    if (buf[i] == '\n')
                        out.flush();
            }
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}
like image 155
vikingsteve Avatar answered Jun 16 '26 17:06

vikingsteve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!