Print null in Java
What happens if you try to print null in Java? It depends.
What the compiler said
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
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.
I’m not making this up.
What the runtime did
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 method throws an exception.
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) ...
With some more research funding I might be able to figure this out!
Go vs. Java: 14 main differences is a brief code comparison.
Java to Go is an in-depth tutorial intended to help Java developers come up to speed quickly with Go.
Share this page: