When I try to print the uninitialized static char array it gives run time error (Null pointer exception) whereas the uninitialized static int array
System.out
is an instance of PrintStream
and this class has a few overloaded println
methods. In your case:
System.out.println(ch);
is using public void println(char x[])
System.out.println(arr);
is using public void println(Object x)
(there is no public void println(int[] x)
method so the closest available type for int[]
which println
can use is Object
).The second method is using
String.valueOf(x);
to get a string representation of the object we want to print and the code of the valueOf
method looks like
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
so it is null-safe (will return the string "null"
if the reference holds null
).
The first method is at some level using
public void write(char cbuf[]) throws IOException {
write(cbuf, 0, cbuf.length);
// ^^^^^^^ this throws NPE
}
and because cbuf
is null
cbuf.length
will throw NullPointerException because null
doesn't have length
(or any other) field.