Monday, 9 March 2015

System.out.println(null) ?

This post demonstrates why System.out.println(null) causes a compilation error and how to resolve.

When you run the statement System.out.println(null), you will see the following compilation error.

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

 Because there are (at least) two print methods that can accept null (one more is println(object)).
Since null can fit in both, the compiler doesn't know which method to use, leading to a compiler error.
The compiler tries to find the most specific version of an overloaded method. Both char[] and String are sub types of Object, so that's why the third method is not considered.

Why compile-time error?

The duty of compiler is to type-check the parameters to the method call. So because of ambiguity, the compiler error.

Possible Method over-loaders that accepts null -

1. public void println(String x) {}
2. public void println(char[] x) {}
3. public void println(Object x) {}

How to resolve?

If you replace the statement System.out.println(null); with any one of the following statements, the code works.

Why not System.out.println((char [])null)?

you will receive the following runtime exception.

Exception in thread "main" java.lang.NullPointerException

Why Null Pointer Exception?

According to Java documentation,
char will not handle null pointer which leads to null pointer exception. Thus println(char[] s) prints the array of characters when s is not a null pointer.

Why println(String s) and println(Object obj) works?

According to Java documentation,
both String and Object handles null pointer.
println(String s) - If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding.

println(Object obj) - The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding.

valueOf(Object obj) -

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();

 If argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

Summary -

Thus char always leads to a null pointer exception when it encounters a null pointer reference.

Try -

public class PrintNull {
 public static void main(String[] args) {
  Object o = null;
  String s = null;
  char[] a = null;

  //System.out.println(null); // Compilation error
  System.out.println(o); // Prints "null"
  System.out.println(s); // Prints "null"
  System.out.println(a); // Throws NullPointerException

Please share your thoughts on this post in the comments section.

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.


Post a Comment