SpringLearner
SpringLearner

Reputation: 13854

Strange behaviour of write method

I was looking some methods of PrintStream class and came across write() and as per the docs to print in the console we need to call System.out.flush();.But my doubt is if I write these lines

System.out.write(40);
System.out.write(10);

Then also ( gets printed.I know 10 represents new line but I wanted to know why it only happens with new line.If I write

 System.out.write(40);
 System.out.write(32); 32 for space then also nothing gets printed.

Demonstration

Upvotes: 2

Views: 94

Answers (4)

4J41
4J41

Reputation: 5095

From the docs.

public void write(int b)

Writes the specified byte to this stream. If the byte is a newline and automatic 
flushing is enabled then the flush method will be invoked.

Upvotes: 1

This appears to be a race condition in PrintStream. The (OpenJDK 6) PrintStream code forces a flush of the underlying OutputStream whenever the output written includes the character \n, but not any other time, and there's no sort of finalizer that ensures that buffered output in the BufferedOutputStream the JVM wraps around standard output gets flushed when the JVM exits.

The code that initializes the System class uses a 128-byte buffer for System.out, and if you output enough characters to fill the buffer (I inserted a 128-count for loop around writing the ( character), you'll see the output on the terminal.

Upvotes: 1

denis.solonenko
denis.solonenko

Reputation: 11775

From the PrintStream.write:

if ((b == '\n') && autoFlush)
   out.flush();
}

So if you write a new-line to a System.out it will be auto-flushed. Btw javadoc says that too:

Writes the specified byte to this stream. If the byte is a newline and automatic flushing is enabled then the flush method will be invoked.

Upvotes: 5

davmac
davmac

Reputation: 20651

Probably the output stream is line-buffered - that is, it automatically flushes when it sees an end-of-line. To guarantee your ouput you should always use flush().

Upvotes: 1

Related Questions