System.out.println() in Java. How does it work?

System.out.println(exp); is used to display messages to the command window. If we go further to the functioning of System.out.println() statement, we will find that:

1. System is a class built into the core Java language and it is defined within the java.lang package.

2. out is a public static member of the System class, of type PrintStream. Thus, the expression System.out refers to an object of type PrintStream.

3. The (overloaded) println method of the PrintStream class accepts an expression as an argument and displays it in String form to the standard output window (i.e., the command-line window from which the program was invoked). There are multiple println overloaded methods with different arguments. Every println makes a call to print method and adds a newline. Internally, print calls write() and write() takes care of displaying data to the standard output window.

We therefore don't need to ever instantiate a System object to print messages to the screen; we simply call the println method on the System class's public static PrintStream member, out.

Now, you might be thinking that can we create an object of PrintStream and call println function with that object to print to the standard output (usually the console)? The answer is NO. When you want to print to the standard output, then you will use System.out. That's the only way. Instantiating a PrintStream will allow you to write to a File or OutputStream you specify, but don't have anything to do with the console.

However, you can pass System.out to PrintStream and then invoke println on PrintStream object to print to the standard output. Following is a small example:

import java.io.*;
public class SystemOutPrintlnDemo
{
  public static void main(String[] args) 
  {
    //creating PrintStream object
    PrintStream ps = new PrintStream(System.out);
    ps.println("Hello World!");
    ps.print("Hello World Again!");
    //Flushes the stream
    ps.flush();
  }
}
 
OUTPUT
======
D:\JavaPrograms>javac SystemOutPrintlnDemo.java
D:\JavaPrograms>java SystemOutPrintlnDemo
Hello World!
Hello World Again!

Hope you have enjoyed reading about the working of System.out.println. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.