在 Java 中,null 字面量用来表示值的缺失。
Java 中的基本数据类型都有默认值,因此永远不可能是null。
按照约定,它们以小写字母开头,例如int。
引用类型保存对象的内存地址,值可以是null。
它们通常以大写字母开头,例如String。
如果试图给基本类型变量赋值null,会导致编译时错误,因为变量始终保持所赋类型的默认值。
// Throws compile time error stating the required type is int, but null was provided
int number = null;
给引用类型变量赋值null不会导致编译时错误,因为引用变量可以为 null。
//No error will occur as the String variable str is nullable
String str = null;
访问值为null的引用变量虽然可以正常编译,但在运行时会导致抛出NullPointerException。
int[] arr = null;
// Throws NullPointerException at runtime
arr.length;
当试图访问一个值为 null 但需要一个对象的引用变量时,会抛出 NullPointerException。
要安全地处理可空的值,应该在使用它们之前先检查是否为null,这可以用==或!=这类相等运算符来完成:
int[] arr = null;
if(arr != null) {
System.out.println(arr.length);
} else {
//Perform an alternate action when arr is null
}