When I try to print the uninitialized static char array it gives run time error (Null pointer exception) whereas the uninitialized static int array
You are actually calling two separate, overloaded System.out.println()
methods. public void println(char[] x)
is overloaded as per the documentation. No specific overloading of println(Object x)
exists for the int[]
arrays.
So, when println()
is called on an integer array, public void println(Object x)
is called. According to the Javadocs:
This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Since the value of the string is null
, the method prints null.
The println()
method works somewhat differently when it takes a character array as a parameter. Superficially, the method itself seems similar:
Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().
However, the print(char[])
method behaves quite differently in key ways:
Prints an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
Thus, it calls a different method. The documentation for print(char[])
explicitly states that in your situation, your exception is thrown:
Throws: NullPointerException - If [input parameter] s is null
Hence, the cause of the difference in behavior.
See Javadocs for more information about the println
and print
methods:
http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println()