如何在Java中检查对象是否为空?
借助“==”运算符,对于参考比较非常有用,它可以比较两个对象。
如果两个引用(对象)都指向同一存储位置,则“==”运算符将返回true,否则,如果两个对象都指向不同的存储位置,则它将返回false。
null是java中引入的关键字,用于检查对象是否为null。
null的不同形式含义是“noobject”或“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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短