当我尝试打印未初始化的static char 数组 时,它给出了运行时错误(空指针异常),而未初始化的static int 数组 给出了空值。为什么?
public class abc {
static int arr[];
static char ch[];
public static void main(String[] args) {
System.out.println(ch); //it gives null pointer exception at run time
System.out.println(arr); //it gives output as "null".
}
}
最佳答案
System.out
是 PrintStream
的一个实例,这个类有一些重载的 println
方法。在你的情况下:
System.out.println(ch);
正在使用public void println(char x[])
System.out.println(arr);
正在使用public void println(Object x)
(没有public void println(int[] x )
方法,因此println
可以使用的int[]
最接近的可用类型是Object
)。
第二种方法是使用
String.valueOf(x);
获取我们要打印的对象的字符串表示,valueOf
方法的代码如下所示
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
因此它是 null 安全的(如果引用持有 null
,将返回字符串 "null"
)。
第一种方法在某种程度上使用
public void write(char cbuf[]) throws IOException {
write(cbuf, 0, cbuf.length);
// ^^^^^^^ this throws NPE
}
并且因为 cbuf
是 null
cbuf.length
会抛出 NullPointerException 因为 null
没有 length
(或任何其他)字段。
关于java - char和int数组的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24833562/