更新時(shí)間:2022-07-15 11:19:26 來源:動(dòng)力節(jié)點(diǎn) 瀏覽2123次
null 在 Java 中的作用有點(diǎn)臭名昭著。遇到可怕的 NullPointerException 問題可能是所有 Java 開發(fā)人員的必經(jīng)之路。我們將在本文后面討論這個(gè)問題,但了解 Null 如何在底層工作可以幫助您了解何時(shí)使用它以及如何避免問題。
在 Java 中,null 是一個(gè)Java字面量,一個(gè)特殊的常量,您可以在任何時(shí)候希望指向不存在的值時(shí)指向該常量。它既不是對象也不是類型,這是 Java 語言新手必須克服的常見誤解。
創(chuàng)建 Null 是為了提供一種方法來指出某些東西的缺失。當(dāng)您在 Java 中聲明一個(gè)變量時(shí),您必須指定它希望存儲在該變量中的類型。您可能會將變量視為存儲兩種主要類型之一的值的容器:
原語是編程語言提供的預(yù)定義數(shù)據(jù)類型。當(dāng)您將變量聲明為原始類型(例如,int、float)時(shí),您的變量直接包含基礎(chǔ)值。
引用是指向所表示的值的指針。當(dāng)您將變量聲明為引用類型時(shí),您存儲的是指向值的地址,而不是值本身。類、數(shù)組和字符串是引用類型的示例。
原始類型不能有 null 值,但 null 可以分配給任何引用類型。這是一個(gè)例子:
//You can assign null to reference types like strings
String myStr = null;
//Similarly you can assign null to the reference type class that points to a primitive type like "int"
Integer a = null;
//But not directly to the primitive type "int"
int myInt = null;
// Will throw the following error: "incompatible types : required int found null"
Null 對象也可以在編譯時(shí)和運(yùn)行時(shí)轉(zhuǎn)換為任何類型。
// Typecasting null to the Integer Class
Integer objInt = (Integer) null;
//Typecasting null to the Double Class
Double objDbl = (Double) null;
雖然從更廣泛的編程意義上理解 null 的概念通常很簡單,作為指出沒有值的一種方式,但在實(shí)踐中,我們必須熟悉 null 在任何給定編程語言中的細(xì)微差別。
null關(guān)鍵字
Null 是 Java 編程語言中的保留關(guān)鍵字。從技術(shù)上講,它是一個(gè)類似于 True 或 False 的對象字面量。
Null 是區(qū)分大小寫的,就像 Java 中的任何其他關(guān)鍵字一樣。
//This will throw a compile-time error
Integer errInt = NULL;
//Returns compile-time error : can't find symbol 'NULL'
Integer Int = null;
//Will assign the integer class Int to a null value
在 Java 中編程時(shí),將 null 寫成小寫非常重要。Null 和 NULL 都會引發(fā)編譯時(shí)錯(cuò)誤。
Null 用作默認(rèn)值
正如原始類型有默認(rèn)值(例如,整數(shù)為 0,布爾值為 false),null 是引用類型的默認(rèn)值。Null 用作任何未初始化引用變量的默認(rèn)值,包括實(shí)例變量和靜態(tài)變量(盡管您仍會收到未初始化局部變量的編譯器警告)。考慮以下 Java 代碼示例。
public class Main {
// Uninitialized variable of reference type will store null until initialized
private static Object emptyObject;
// Uninitialized integer is a primitive type so it will store a value (e.g., 0)
private static int emptyInt;
public static void main(String[] args) {
// Initialized integer with value 20.
int regInt = 20;
System.out.println(regInt);
// Prints 20
System.out.println(emptyInt);
// Prints 0
System.out.println(emptyObject);
// Prints null
}
}
將 null 與 instanceOf 運(yùn)算符一起使用
如果您想知道一個(gè)對象是否是特定類、子類或接口的實(shí)例,您可以使用 instanceOf 運(yùn)算符進(jìn)行檢查。需要注意的是,如果在任何具有空值或空文字本身的引用變量上使用 instanceOf 運(yùn)算符,它將返回 false 。
當(dāng)您指向具有空值的對象時(shí),Java 中會拋出 java.lang.NullPointerException。Java 程序員在忘記初始化變量時(shí)通常會遇到這種臭名昭著的指針異常(因?yàn)?null 是未初始化引用變量的默認(rèn)值)。
程序員可能遇到 NullPointerException 的常見場景包括:
調(diào)用未初始化的變量
使用空對象訪問或修改數(shù)據(jù)字段或成員
將空對象作為參數(shù)傳遞給方法
使用空對象調(diào)用方法
同步一個(gè)空對象
拋出一個(gè)空對象
將空對象視為 Java 數(shù)組
那么如何避免 NullPointerException 呢?簡單的。不要返回空值。
除了確保所有變量都正確初始化并且所有對象引用都指向有效值這一顯而易見的任務(wù)(盡管不一定容易)之外,您還可以使用一些技術(shù)來處理 NullPointerException。
檢查方法的參數(shù)
private static void CheckNull(String myStr) {
if (myStr != null) {
System.out.println(myStr.length());
} else {
// Perform an alternate action when myStr is null
System.out.println “Please pass a valid string as an argument”
}
}
使用三元運(yùn)算符
//boolean expression ? value1 : value2;
String myStr = (str == null) ? "" : str.substring(0, 20);
//If str’s reference is null, myStr will be empty. Else, the first 20 characters will be retrieved.
返回空集合而不是 null
返回空集合而不是 null 值被認(rèn)為是最佳實(shí)踐。
public class emptyString {
private static List<Integer> numbers = null;
public static List<Integer> getList() {
if (numbers == null)
return Collections.emptyList();
else
return numbers;
}
}
通過以上介紹,相信大家對Java中的null已經(jīng)有所了解,大家如果對此比較感興趣,想了解更多相關(guān)知識,不妨來關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java教程,里面的課程內(nèi)容細(xì)致全面,很適合小白學(xué)習(xí),希望對大家能夠有所幫助。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743