Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 330
Sukhendu Rana Avatar asked Jan 20 '15 08:01

Sukhendu Rana


2 Answers

It's behaving as it's documented to. PrintStream.println(String) is documented as:

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().

PrintStream.print(String) is documented as:

Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

When in doubt, read the documentation :)

like image 148
Jon Skeet Avatar answered Sep 22 '22 00:09

Jon Skeet


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();
}
like image 25
Eran Avatar answered Sep 22 '22 00:09

Eran