August 24, 2013

System.out.println : So called SOP/sysout

Widely used statement in Java and interestingly its one of the most number of times compiled statement in the history of java, also commonly asked interview question.

Here we will try to understand some interesting fact about sysout.

Inside System Class  (Check with JDK Source CodeJava Doc

public final static PrintStream out = nullPrintStream();

As you can see out is a static member of System Class , now you can understand the significance of System.out and println (member function of PrintStream Class).

How Println Looks. (Note : println is overloaded with different input arguments check with jdk source code)

public void println(String x) {
	synchronized (this) {

As you can see the println Method is synchronized. That’s why you shouldn’t write systouts in your code otherwise you will hit the performance.

Lets see why this method is synchronized.
If two thread contains:


Then without Synchronization the output may looks below

Lets understand the output steam.

public final static PrintStream out = nullPrintStream();

as you can see out is assigned to nullPrintStream(), so how it will write to console.

Default output stream is set as below within the System Class (method : initializeSystemClass )

setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));

Brain Work :

As you have seen there is a method to set the output stream. So you can now change the default output stream..

Below program will change the default output stream to FileOutput Stream. i.e. whenever you write something to sysout the output will go to a file instead of console.

package in.bibek;


public class SysoutTest {

	public static void main(String[] args) {
		System.out.println("Writing to Console");

		try {
		      System.setOut(new PrintStream(new FileOutputStream("e:/output.txt")));
		      System.out.println("Writing to File instead of Console");
		    } catch(Exception e) {

Enjoy 🙂

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.