Sameer Sameer
Sameer Sameer

Reputation: 57

char array vs int array in java while printing the base value of array

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);
    }
}

Upvotes: 3

Views: 573

Answers (2)

Amit Bhati
Amit Bhati

Reputation: 5649

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.

Upvotes: 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 :)

Upvotes: 3

Related Questions