java里对象为空语句_如何在Java中检查对象是否为空?

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

如果两个引用(对象)都指向同一存储位置,则“ ==”运算符将返回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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值