Printing a char[] behaves differently than other arrays, since PrintStream (which is the type of the System.out instance) has a specific method for printing char arrays - public void println(char x[]) - while for other arrays the general method for Objects is used - public void println(Object x).
println(Object x) prints the String "null" when passing to it a null reference.
/**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>Object</code> to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
/**
* Returns the string representation of the <code>Object</code> argument.
*
* @param obj an <code>Object</code>.
* @return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
println(char x[]) throws a NullPointerException when passing to it a null reference.
public void println(char x[]) calls public void print(char s[]) which calls public void write(char buf[]), which throws the NullPointerException when buf.length is evaluated:
/*
* The following private methods on the text- and character-output streams
* always flush the stream buffers, so that writes to the underlying byte
* stream occur as promptly as with the original PrintStream.
*/
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();
}
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
BTW, the Javadoc of print(char s[]), which is the first method called by public void println(char x[]), mentions the NullPointerException exception :
void java.io.PrintStream.print(char[] s)
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.
Parameters:
s The array of chars to be printed
Throws:
NullPointerException - If s is null