Ответ 1
Печать char[]
ведет себя иначе, чем другие массивы, поскольку PrintStream
(который является типом экземпляра System.out
) имеет специальный метод для печати char
массивов - public void println(char x[])
- в то время как для других массивов используется общий метод для Object
- public void println(Object x)
.
println(Object x)
печатает строку "null" при передаче ей ссылки null
.
/**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object 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[])
выдает a NullPointerException
при передаче ему ссылки null
.
public void println(char x[])
вызывает public void print(char s[])
, который вызывает public void write(char buf[])
, который выдает NullPointerException
при оценке buf.length
:
/*
* 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, Javadoc print(char s[])
, который является первым методом, называемым public void println(char x[])
, упоминает исключение NullPointerException
:
void java.io.PrintStream.print(char [] s)
Печатает массив символов. Символы преобразуются в байты в соответствии с кодировкой символов по умолчанию для платформы, и эти байты записываются точно так же, как метод write (int).
Параметры:
s Массив символов для печати
Выдает:
NullPointerException - если s равно null