How to print null in Java

What happens if you try to print a null pointer in Java? It depends.

The following line will not compile:

System.out.println(null);

This is the message from my compiler:

reference to println is ambiguous, both
method println(char[]) in java.io.PrintStream and
method println(java.lang.String) in java.io.PrintStream match

Character arrays, strings, and objects

In fact, println(java.lang.Object) in java.io.PrintStream is yet another match, but Java has a way of choosing between that one and each of the two methods above. It’s just the string and the character array parameters that cause ambiguity as character arrays and objects can happily coexist.

The following lines will compile:

class NullPrint {
public static void main( String args[] ) {
Object o = null;
String s = null;
System.out.println(o);
System.out.println(s);
}
}

Here, null has been explicitly cast to a string or object, which leaves no ambiguity. The following command would also work:

System.out.println((String)null)

The following will not compile:

class NullPrint {
public static void main( String args[] ) {
char[] a = null;
System.out.println(a);
}
}

The char array null cannot be printed by the PrintStream since it causes a NullPointerException.