Output in Java

The Java standard System class has two built-in static methods to interact with the console.

  1. out.print()
  2. err.print()

Method out.print()

The out.print() method is used to print anything to the console.

  1. out.print() – Print anything without newline character.
  2. out.println() – Prints anything with extra one newline character at the end of line.
  3. out.printf() – Works just like C language printf() function.
public class Output {

    public static void main(String[] args) {

        // Without new line
        System.out.print("Line without new line");
        
        // Move to new line
        System.out.print("\n");
        
        // With new line
        System.out.println("Line with new line");
        
        // Using printf
        System.out.printf("My name is %s, and i, am %d year old", "John", 24);
    }
}

Output

Line without new line
Line with new line
My name is John, and i, am 24 year old

Method err.print()

The err.print() method is used to print errors on the console.

Just like out.print() method here you can also do:

  1. err.print() – Print error line without newline character.
  2. err.println() – Prints error line with extra one newline character at the end of line.
  3. err.printf() – Works just like C language printf() function.
public class ErrorOutput {

    public static void main(String[] args) {

        // Without new line
        System.err.print("Error line without new line");

        // Move to new line
        System.err.print("\n");

        // With new line
        System.err.println("Error line with new line");
        
        // Using printf
        System.err.printf("Error : %s, at line no %d", "NullPointerException", 10);
    }
}

Output

Error line without new line
Error line with new line
Error : NullPointerException, at line no 10