Monday 11 July 2022

Why System.out.println() is not throwing NullPointerException on null references?

If you are a Java programmer, you might have used ‘System.out.println’ method to print the string representation of an object. But did you get a doubt any time, ‘what happen when I pass a null reference to the System.out.println’ method.

 


Example 1: Print null reference string using System.out.println method.

String str = null;

System.out.println(str);

 

Example 2: Print null object using System.out.println method.

Object obj = null;

System.out.println(obj);

 

Example 2: Print null collection using System.out.println method.

List<String> list = null;

System.out.println(list);

 

In all the above cases, Java print the value "null" to the console. Let’s dig into the code and try to understand.

 

For the example 1, System.out.println is implemented like below.

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}

 

As you observe above snippet, println(String x) internally calls the print method, which prints "null" for a null String :

 

For the example 2, and example 3 Java internally use ‘String.valueOf’ method which prints "null" for a null String. Implementation is given below.

 

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

 

String.valueOf method is implemented like below.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Find the below working application.

 

SysOutDemo.java

package com.sample.app;

import java.util.List;

public class SysOutDemo {

	public static void main(String[] args) {
		String str = null;
		System.out.println(str);

		Object obj = null;
		System.out.println(obj);

		List<String> list = null;
		System.out.println(list);

	}

}

Output

null
null
null



You may like

Interview Questions

Quick guide to generate random data in Java

What are the different cache eviction strategies?

How to call super class method from sub class overriding method?

Can an enum has abstract methods in Java?

Can enum implement an interface in Java?

What happen to the threads when main method complete execution

No comments:

Post a Comment