Difference Between System.out.println() and System.err.println() in Java

If we are using a simple Java console application, both outputs will be the same but we can reconfigure the streams so that for example, prints to the console but System.err writes to a file. In this section, we will discuss the differences between System.out.println() and System.err.println() in Java.

1. Purpose

  • System.out.println(): Used for printing general output, like program results or messages to the user.
  • System.err.println(): Used for printing error messages or diagnostic information.

2. Output Stream

  • System.out.println(): Prints to the standard output stream (stdout).
  • System.err.println(): Prints to the standard error stream (stderr).

3. Redirection

  • System.out.println(): Output can be redirected to a file or another process using standard redirection techniques.
  • System.err.println(): Output can also be redirected, but it's often handled separately to ensure error messages are visible even if standard output is redirected.

4. Use Case

  • System.out.println(): It is used for displaying information that is part of the normal program flow.
  • System.err.println(): It is used for reporting issues, exceptions, or warnings that need attention.

System.out.println() Vs. System.err.println()

FeatureSystem.out.println()System.err.println()
PurposeGeneral outputError and debugging output
Stream TypeStandard output streamStandard error stream
UsageUsed for regular program outputUsed for printing error messages and diagnostics
Default DestinationConsoleConsole
RedirectionCan be redirected separately from System.errCan be redirected separately from System.out
BufferingBuffered by defaultUnbuffered by default
Output DistinctionLess suitable for distinguishing error messagesSuitable for distinguishing error messages
Typical Use CasesDisplaying normal program output like results, logsPrinting stack traces, error messages, warnings
Code ExampleSystem.out.println("Hello, World!");System.err.println("An error occurred!");
Performance ImpactMinor impact due to bufferingMay have a slight performance impact

Example

File Name: SystemOutput.java

Output:

 
This message is back to the console.
This error message is back to the console.   

error.txt

Output.txt

 
This is a regular message to the file.   

Conclusion

It is easier to write more reliable and maintainable Java programs when we know the differences between System.out.println() and System.err.println(). To ensure that error messages and diagnostics are easily distinguished from regular program output-a crucial feature for debugging and logging-System.err.println() should be used.