Sukhendu Rana Sukhendu Rana - 17 days ago 5
Java Question

Why doesn't System.out.println() throw NullPointerException?

This might be a very basic question, but I still don't know the answer.

String abc = null;
System.out.println(abc);


Why does
System.out.println
print "null" and does not throw
NullPointerException
?

Answer

Because it eventually reaches the print method, which prints "null" for a null String :

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

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

The same behavior exists for printing of any null reference (in this case the "null" String is returned by String.valueOf(null) :

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

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