Java 中的 null 看着很簡單,也容易被很多人忽略,有時候也讓人不知所措。
Java 中的空 null
我們先看幾段代碼吧。
1. 例一:null 的對象性
public class NullTest {
public static void greet() {
System.out.println("Hello world!");
}
public static void main(String[] args) {
((NullTest) null).greet();
}
}
上面的程序看起來似乎應該拋出 NullPointerExceptioin 異常,因爲其 main 方法是在常量 null 上調用 greet 方法,而你是不可以在 null 上調用方法的,對嗎?
其實編譯和運行都沒有問題。運行結果爲:
Hello world!
2. 例二:null 的初始化
public static void main(String[] args) {
String str=null;
Integer in=null;
Double dou=null;
String str1=(String)null;
Integer in1=(Integer)null;
Double dou1=(Double)null;
int in2=null;
int in3=(int)null;
}
發現 null 可以初始化引用類型,也可以轉換爲任意的引用類型。但不能給基本類型賦值,或者轉換爲基本類型。
3. 例三:null 的相等性
public static void main(String[] args) {
System.out.println(null==null);
System.out.println(null!=null);
System.out.println(Double.NaN==Double.NaN);
System.out.println(Double.NaN!=Double.NaN);
}
結果該是什麼呢?
true
false
false
true
4. 例四:null 不是引用類型
public static void main(String[] args) {
Integer in=null;
if(in instanceof Integer) {
System.out.println("null is integer");
}else {
System.out.println("null is not integer");
}
}
結果是:
null is not integer
5. 例 5:不可傳遞
public static void main(String[] args) {
Integer i=null;
int k=i;
System.out.println(k);
}
報錯:
Exception in thread "main" java.lang.NullPointerException
NullTest.main(NullTest.java:6)
6. 例 6:null 的數組
public static void main(String[] args) {
String[] arr1={"abc","123",null,"sky"};
boolean flag=false;
for (String s1 : arr1) {
if(s1.equals("sky")) {
flag=true;
break;
}
}
System.out.println(flag);
}
運行時報錯
Exception in thread "main" java.lang.NullPointerException
at NullTest.main(NullTest.java:8)
修改成
public static void main(String[] args) {
String[] arr1={"abc","123",null,"sky"};
boolean flag=false;
for (String s1 : arr1) {
if("sky".equals(s1)) {//對比前後順序
flag=true;
break;
}
}
System.out.println(flag);
}
就沒有問題了。
追根到底
JSL 3.10.7 定義了 null
The null type has one value, the null reference, represented by the null literal null, which is formed from ASCII characters.
JSL 4.1 做了補充:
1.There is also a special null type, the type of the expression null (§3.10.7, §15.8.1), which has no name.
Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.
注:null 是一種特殊類型,它的表達式爲 null,但沒有名稱。因爲 null 類型沒有名稱,故不能聲明一個 null 類型(如 private null a),也不能將一個類型轉爲 null 類型。
2.The null reference is the only possible value of an expression of null type.
注:使用 null 類型的唯一方式是使用 null 引用(如 private Integer a = null);
3.The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).
注:空引用可以賦值給其他任意類型,如 String,Integer,Class 等等。
4.In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.
注:其實,程序開發者可以忽略 null 類型,僅僅將它當作一種可以賦值給其他任意類型的特殊引用。