借助“ ==”运算符,对于参考比较非常有用,它可以比较两个对象。

如果两个引用(对象)都指向同一存储位置,则“ ==”运算符将返回true,否则,如果两个对象都指向不同的存储位置,则它将返回false。

null是java中引入的关键字,用于检查对象是否为null。

null的不同形式含义是“ no object”或“ unknown”。

我们将看到一个检查对象是否为空的程序。

例:

public class ToCheckNullObject {
public static void main(String[] args) {
//我们用null创建一个字符串对象
String str1 = null;
//通过使用==运算符比较两个对象
//借助null,我们可以轻松识别
//object是否为null-
if (str1 == null) {
System.out.println("Given object str1 is null");
System.out.println("The value of the object str1 is " + str1);
} else {
System.out.println("Given object  str1 is not null");
System.out.println("The value of the object str1 is " + str1);
}
//我们创建了一个具有指定值的字符串对象
String str2 = "Welcome in Java World";
//通过使用==运算符比较两个对象
//借助null,我们可以轻松识别
//object是否为null-
if (str2 == null) {
System.out.println("Given object str2 is null");
System.out.println("The value of the object str2 is " + str2);
} else {
System.out.println("Given object str2 is not null");
System.out.println("The value of the object str2 is " + str2);
}
//我们创建了一个具有指定值的字符串对象
String str3 = " ";
//通过使用==运算符比较两个对象 and
//在null的帮助下,我们将轻松识别
//object是否为null-
if (str3 == null) {
System.out.println("Given object str3 is null");
System.out.println("The value of the object str3 is " + str3);
} else {
System.out.println("Given object str3 is not null");
System.out.println("The value of the object str3 is " + str3);
}
//我们用null创建一个整数对象
Integer i1 = null;
//通过使用==运算符比较两个对象 and
//在null的帮助下,我们将轻松识别
//object是否为null-
if (i1 == null) {
System.out.println("Given object i1 is null");
System.out.println("The value of the object i1 is " + i1);
} else {
System.out.println("Given object i1 is not null");
System.out.println("The value of the object i1 is " + i1);
}
//我们创建了一个具有指定值的整数对象
Integer i2 = 100;
//通过使用==运算符比较两个对象 and
//在null的帮助下,我们将轻松识别
//object是否为null-
if (i2 == null) {
System.out.println("Given object i2 is null");
System.out.println("The value of the object i2 is " + i2);
} else {
System.out.println("Given object i2 is not null");
System.out.println("The value of the object i2 is " + i2);
}
}
}

输出结果

D:\Programs>javac ToCheckNullObject.java
D:\Programs>java ToCheckNullObject
Given object str1 is null
The value of the object str1 is null
Given object str2 is not null
The value of the object str2 is Welcome in Java World
Given object str3 is not null
The value of the object str3 is
Given object i1 is null
The value of the object i1 is null
Given object i2 is not null
The value of the object i2 is 100