简体   繁体   中英

Java 'System.err.format' with '%n' followed by 'System.out.println' , println prints in the middle

I am very new to Java.

I am using Ubuntu 16.04, JDK 8u101, Netbeans8.1.

When trying this code:

public static void main(String[] args) {
    System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line ");
    System.out.println("Shouldn't this be the third line,prints at 2nd line");
}

The output is:

This Prints At 1st Line 
Shouldn't this be the third line, but prints at 2nd line
This Prints At 3rd Line, Shouldn't this be In 2nd Line

Why does " System.out.println " print in the middle? Shouldn't it print last.

I tried with " %n " at the end & System.err.flush() like this:

System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n");
System.err.flush();
System.out.println("Shouldn't this be the third line,prints at 2nd line");

Still same output.

You aren't calling flush() between the println() calls and System.out and System.err are both ( independently ) buffered PrintStream (s).

// and you need a %n on the end to make 3 lines.
System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n"); 
System.err.flush(); // <-- only needed if the previous write doesn't have
                    //     an implicit flush(); newline (%n) does.
System.out.println("Shouldn't this be the third line,prints at 2nd line");

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