gpt4 book ai didi

java - 打印数组基值时java中的char数组与int数组

转载 作者:行者123 更新时间:2023-11-30 06:50:48 24 4
gpt4 key购买 nike

在 java 中打印 char 数组时它给出空指针异常但在整数数组的情况下它打印 null

public class Test {
char c[];
int a[];
//while printing c it gives null pointer exception
public static void main(String[] args) {
System.out.println(new Test().c);
// in case of integer it prints null
System.out.println(new Test().a);
}
}

最佳答案

正如 4CaSTLe 所说,原因是

System.out.println(...);

不仅仅是一种方法,而是许多采用不同参数的不同方法

enter image description here

这在 java 中称为方法重载

源码背后:

println 正在调用 print

print 正在调用 write

如果 write(..) 使用的是 char[] 那么就会发生 NPE,因为代码正在尝试(除其他外)获取数组的长度这是空引用

 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();
}
}
}

另一方面,打印 int[] 将以调用 println(Object x) 结束,其中 String.valueOf被调用

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();
}

valueOf(null) 返回 null:)

关于java - 打印数组基值时java中的char数组与int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40951718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com