简体   繁体   中英

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?

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM