javasystem.outsystem.err

Difference in Processing of System.err.print and System.out.print


Is there a differnece how System.err.print and System.out.print are processed while getting executed? I have a twodimensional array of Integers ranged between 2 and 20. The Array is printed as a Matrix and all Integers >=10 shall be printed red, using System.err.print. If doing so the output looks like this:

 7   11  15  12  12  12  11  16  17  17  13   4   7 
 9    8   4 
 9  
 9    4  10 
12    4  16  12  10 

with all int>=10 being red.
instead of looking like this

 11   7   4  15   7 
  9  12   8  12   4 
  9  12  11  16  17 
 17   9   4  13  10 
 12   4  16  12  10   

without the red marks i want.

Both use the same array, first gets printed with this code:

public static void printArray2(int ar[][]) {
    if (ar == null)
        System.exit(0);
    for (int i = 0; i < ar.length; i++) {
        for (int j = 0; j < ar[i].length; j++) {
            if (ar[i][j] < 10)
                System.out.print("  " + ar[i][j] + "\t");
            else
                System.err.print(" " + ar[i][j] + "\t");
        }
        System.out.println();
    }
}

while the second output gets printed with this code

public static void printArray(int ar[][]) {
    if (ar == null)
        System.exit(0);
    for (int i = 0; i < ar.length; i++) {
        for (int j = 0; j < ar[i].length; j++) {
            if (ar[i][j] < 10)
                System.out.print("  " + ar[i][j] + "\t");
            else
                System.out.print(" " + ar[i][j] + "\t");
        }
        System.out.println();
    }
}

Is there way to prevent the unformmated output while still using System.err.print?


Solution

  • Basically those two streams represent different consoles.

    What really happens when you print to them might very much depend on the JVM implementation or the underlying operating system.

    In that sense: your real problem is your assumption that you can use the consoles like this.

    The purpose of the error console is: you print important error messages there. As an alternative approach - check out if you can use some "ncurses" like library for your application (see here as starting point). In other words: instead of mis-using stderr like this - look into ways to gain more control over stdout. So that you can print in colours on one console, instead of two.