Java: Print null
What happens if you try to print a null pointer in Java? It depends.
The following line will not compile:
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
java.io.PrintStream is yet another match,
but Java has a way of chosing between that one and each of the two methods above.
It’s just the string and the character array parameters that cause ambiguity;
character arrays and objects can happily coexist.
The following lines will compile:
Object o = null; String s = null; System.out.println(o); System.out.println(s);
Here is the output:
The following will also compile:
char a = null; System.out.println(a);
But this actually throws an exception in runtime:
Exception in thread "main" java.lang.NullPointerException at java.io.Writer.write(Writer.java:127) at java.io.PrintStream.write(PrintStream.java:470) at java.io.PrintStream.print(PrintStream.java:620) at java.io.PrintStream.println(PrintStream.java:759) ...