觸發條件:當壹個對象為空時,?當妳試圖調用壹個對象的方法,或者訪問或修改壹個對象的屬性時,妳將拋出壹個空指針異常。
這個異常的解決方案:?
盡量避免使用空對象,
或者在使用它之前判斷它是否為空,
或者使用try catch捕獲異常並處理它。
參考碼
錯誤演示
公共?班級?演示?{
公共?靜電?作廢?main(String[]?args)?{
字符串?str?=?null
if(str.equals("ABC "))?{?//str為空。調用str的equals方法。您將報告壹個錯誤。
System.out.println("字符串的內容是ABC ");
}別的?{
System.out.println("字符串的內容不是ABC ");
}
}
}求解演示1
公共?班級?演示?{
公共?靜電?作廢?main(String[]?args)?{
字符串?str?=?null
if("ABC "。equals(str))?{?//使用非空對象“ABC”將他的equals方法設置為空。
System.out.println("字符串的內容是ABC ");
}別的?{
System.out.println("字符串的內容不是ABC ");
}
}
}演示2:在調用方法和訪問屬性之前判斷是否為空。
公共?班級?演示?{
靜電?字符串?str 1;
公共?靜電?作廢?main(String[]?args)?{
if(str1!=null)?{//通話?其長度法
system . out . println(str 1 . length());
}別的?{
System.out.println("str1對象為空");
}
}
}演示3
進口?Java . util . scanner;
公共?班級?演示?{
靜電?字符串?str 1;
公共?靜電?作廢?main(String[]?args)?{
試試?{
system . out . println(str 1 . length());
}catch(NullPointerException?e)?{
System.out.println("str1為空...請指定壹個值... ");
掃描儀?sc?=?新的?掃描儀(system . in);
str1?=?sc . nextline();
System.out.println("str1的長度為"+str 1 . length());
}
}
}
//str1為空...請指定壹個值。..
//ABC
//str 1的長度為:3