Weird behavior when using System.err.println()

603 Views Asked by At

I thought that difference between System.out.println() and System.err.println() is simply in how messages are printed to console. Meaning err prints error messages (red color), while out prints standard messages. It has come to my notice that they are less alike than expected (for example, err messages would be always printed before out messages).

But there is one example I am particularly confused about. Say I have this simple program:

Scanner scanner = new Scanner(System.in);

while (true) {
    int num = scanner.nextInt();
    if (num > 0) {
        System.out.println("All good, bye");
        break;
    } else {
        System.out.println("Number must be possitive!");
        System.out.print("New try:");
    }
}

OUTPUT (from my testing):

enter image description here


But when I make literally same code and just change message "Number must be possitive" to be printed using System.err.println():

Scanner scanner = new Scanner(System.in);

while (true) {
    int num = scanner.nextInt();
    if (num > 0) {
        System.out.println("All good, bye");
        break;
    } else {
        System.err.println("Number must be possitive!");
        System.out.print("New try:");
    }
}

OUTPUT (from my testing):

enter image description here

I can't figure out how it is making these weird prints. Can someone tell me what am I missing?

2

There are 2 best solutions below

0
the Hutt On

I think it's because two separate streams writing to same console.

int i = 5;
while (--i>0) {
        System.out.println("Number must be possitive!");
        System.out.println("New try:");
}

System.out.println("\n\n with two separate streams \n");
i=5;
while (--i>0) {
    System.err.println("Number must be possitive!");
    System.out.println("New try:");
}

Output:

Number must be possitive!
New try:
Number must be possitive!
New try:
Number must be possitive!
New try:
Number must be possitive!
New try:


 with two separate streams 

Number must be possitive!
New try:
New try:
Number must be possitive!
Number must be possitive!
New try:
Number must be possitive!
New try:

As both streams are not in synch the order in which they write is not guaranteed.

1
Aldin On

I would suggest checking your IDE settings when it comes to console. It happens to be running just fine for me:

Example of mine compilation

The code that I used is basically same:

    import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
        
        System.out.print("Enter the number:");
        Scanner scanner = new Scanner(System.in);
    while (true) {
        int num = scanner.nextInt();
        if (num > 0) {
            System.out.println("All good, bye");
            break;
            
        } else {
            System.err.println("Number must be possitive!");
            System.out.print("New try:");
            
        }
        
    }
    }
}