打印char[]
的行为与其他数组不同,因为PrintStream
(即System.out
实例的类型)具有用于打印char
数组的特定方法 - public void println(char x[])
,而对于其他数组,则使用Object
的通用方法 - public void println(Object x)
。
println(Object x)
在传递null
引用时打印字符串"null"。
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
println(char x[])
在传递给它一个 null
引用时会抛出 NullPointerException
。
public void println(char x[])
调用 public void print(char s[])
,该方法又调用 public void write(char buf[])
。当评估 buf.length
时,会抛出 NullPointerException
。
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;
}
}
顺便提一下,print(char s[])
方法是 public void println(char x[])
调用的第一个方法,在文档注释中提到了 NullPointerException
异常:
void java.io.PrintStream.print(char[] s)
打印字符数组。根据平台默认的字符编码将字符转换为字节,并按照 write(int)
方法的方式精确地写入这些字节。
参数:
s 要打印的字符数组
抛出:
NullPointerException - 如果 s 为 null
print((String)null)
不会抛出异常;char[]
应该表现得一样。这可能是早期实现中的一个错误,他们必须保留。 - ZhongYuprint(char[])
已经与print(Object)
有所不同,因为后者总是表现得像使用了toString
或类似的方法,而前者实际上并没有。也许这个糟糕的设计选择是使方法名称相同的原因。 - ajb