3

In java while printing char array it gives null pointer exception but in case of integer array it prints null

public class Test {
    char c[];
    int a[];
    //while printing c it gives null pointer exception
    public static void main(String[] args) {
        System.out.println(new Test().c);
        //  in case of integer it prints null  
        System.out.println(new Test().a);
    }
}

2 Answers2

3

As 4Castle suggest, the reason is that

System.out.println(...);

is not just 1 method but instead many many different methods taking different parameters

enter image description here

This is known in java as method overloading

Behind the source code:

println is calling print

print is calling write

If write(..) is using a char[] then a NPE is happening because the code is trying (among others) to get the length of the array which is null referenced

 private void write(char buf[]) {
        try {
            synchronized (this) {
                ensureOpen();
                textOut.write(buf);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush) {
                    for (int i = 0; i < buf.length; i++)
                        if (buf[i] == '\n')
                            out.flush();
                }
            }
        }

On the other hand, printing a int[] will be ending up into a calling println(Object x) where String.valueOf is invoked

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

and as you can see

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

the valueOf(null) returns null :)

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
3

As suggested, the reason for the behavior of println in your question, is different overloaded System.out.println(...) methods are getting called.

  • In case of int[] :- public void println(Object x)

  • In case of char[] :- public void println(char x[])

Don't want to copy paste from Jdk source code.

  1. First method first calls String.valueOf(x), which returns null in your case. Then there is a print(s) method call which print null if argument passed is null.

  2. Second method throws NPE, null pointer exception in case passed argument is null.

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45