[英]char array vs int array in java while printing the base value of array
在Java中,當打印char數組時,它給出了null指針異常,但是在整數數組的情況下,它打印了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(...);
不只是一種方法,而是許多采用不同參數的不同方法
這在Java中稱為方法重載
源代碼背后:
println正在調用print
打印正在調用寫
如果write(..)
使用char[]
則發生NPE,因為代碼正嘗試(其中包括)獲取被引用為null的數組的長度。
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 :)
如所建議的,您問題中println行為的原因是調用了不同的重載System.out.println(...)方法 。
如果是int []:- public void println(Object x)
在char []的情況下: -public void println(char x [])
不想從Jdk源代碼復制粘貼。
第一個方法首先調用String.valueOf(x),在您的情況下返回null。 然后有一個print方法調用,如果傳遞的參數為null,則打印null。
第二種方法拋出NPE,如果傳遞的參數為null,則返回null指針異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.