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 to use 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");
}

Conclusion:

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 is " System.out.println" printed in the middle? Do not print last time.

I tried with %n"at the end and System.err.flush()as follows:

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");

The same conclusion.

+4
source share
1 answer

You do not call flush()between calls println(), and System.outand System.errare 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");
+5
source

Source: https://habr.com/ru/post/1654200/


All Articles