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 and
method println(java.lang.String) in match

In fact, println(java.lang.Object) in 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; 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;

Here is the output.


The following will also compile.

char[] a = null;

But this method throws an exception.

Exception in thread "main" java.lang.NullPointerException

With some more research funding I might be able to figure this out!

Key takeaways

Method overloading and inheritance are two fairly complicated constructs. If you combine them, things can get out of control. And this can happen when you least expect it.

Here are two rules of thumb from Effective Java that can help.

A safe, conservative policy is never to export two overloadings with the same number of parameters. (Item 41)
Use composition and forwarding instead of inheritance, especially if an appropriate interface to implement a wrapper class exists. (Item 16)

Further reading

Go vs. Java: 15 main differences is a brief code comparison.

This Java to Go in-depth tutorial is in­tended to help Java deve­lopers come up to speed quickly with Go.

Share this page: