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()
println()
is overloaded and tries to print the array as a string, whereas theint[]
overload simply prints it as an array. Refer to C++'sstd::cout::operator<<
when called withchar *
or a genericvoid *
pointer. – user3477950 2 hours agoprintln
overloading, and nothing to do with the arrays themselves.int[]
andchar[]
are essentially identical save for the fact thatint
is 4-byte signed data andchar
is 2-byte unsigned data. – Hot Licks 2 hours ago