Chatterjee
Chatterjee

Reputation: 299

Why does System.out.print cause autoflush?

System.out is a PrintStream object. I read the documentation on PrintStream. What I don't get is why System.out.print causes the buffer to be flushed? Shouldn't that happen only for println?

Upvotes: 4

Views: 2617

Answers (3)

user207421
user207421

Reputation: 310884

Shouldn't that happen only for println?

The Javadoc doesn't say when it won't be flushed. And it says it will be flushed on a println() or a newline.

Upvotes: 1

Bob Gilmore
Bob Gilmore

Reputation: 13758

At the risk of repeating the facts that have already been noted, let me try to interpret the doc a little differently...

It seems that it's only at PrintBuffer creation time (that is, during constructor invocation) that the autoFlush behavior of a PrintStream can be set.

Also, as you've pointed out, the documentation states that, when calling any of the various public PrintBuffer constructors, not specifying the autoflush state will result in a non-autoflushing PrintStream being created.

However, in the System.out case, you are not calling the construtor for the PrintBuffer. The java.lang.System class instantiates the "out" PrintStream on VM startup. That means that, when you request the PrintStream object that the System object stores in its "out" field, you have no idea which constructor was called, and therefore no idea of the autoflush state of the stream that gets handed to you when you ask for it.

I agree, it would have been really nice if the doc for java.lang.System specified that the stream contained in its "out" field has its autoflush behavior set to true. But that's not a "requirement," any more than I'm required to document whether the JButton returned from my (hypothetical) myCrazyPanel.getTheChangeColorsButton() is enabled or disabled. Yeah, buttons are enabled by default, but you're not allowed to complain if the JButton is disabled. Same thing here.

Upvotes: 1

Clark
Clark

Reputation: 1365

You want the buffer to be flushed when you call System.out.print() because you want it to be printed. When I call print, I want it to print something. If it didn't flush, it would just remain in the buffer and I wouldn't see anything.

Check out flush here.

Basically it's a guarantee that it'll get printed immediately.

Upvotes: 0

Related Questions