Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing null in java [duplicate]

On execution of following line :

    System.out.println(null);

the result comes out to be null printed on console.

Why does that happen?

like image 961
Gaurav Naugain Avatar asked Sep 07 '11 05:09

Gaurav Naugain


2 Answers

Telling from the sources of OpenJDK 1.6.0_22:

PrintStream:

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

String:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}
like image 77
kay Avatar answered Oct 20 '22 21:10

kay


Actually, at least in java version 1.8.0, System.out.println(null); should not print null. You would get an error saying something like:

reference to println is ambiguous, both method println(char[]) in PrintStream and method println(String) in PrintStream match. enter image description here

You would have to cast as follows: System.out.println((String)null); See coderanch post here. I suppose you could also do System.out.println(null+""); to accomplish same.

like image 41
sedeh Avatar answered Oct 20 '22 20:10

sedeh