When I try to print the uninitialized static char array it gives run time error (Null pointer exception) whereas the uninitialized static int array
The answer exists in the PrintWriter
source code (of which System.out
is an instance).
Start with the fact that the uninitialized arrays, as reference variables, are given the default of null
.
The println(char[])
(eventually) attempts to call .length
on the passed in array. It's null, resulting in the NullPointerException
. println(char[])
(eventually) calls write(char[])
:
public void write(char buf[]) {
write(buf, 0, buf.length);
}
There is no overload of println
matching int[]
, but there is a println(Object)
. There it (eventually) attempts String.valueOf
, passing the null
reference, so String.valueOf
takes the null
and returns the String
"null"
. println(Object)
calls print(Object)
:
public void print(Object obj) {
write(String.valueOf(obj));
}