什么情况下不能用 isEmpty

本文通过实验展示了在Java中使用`== null`判断字符串为null的错误,强调了`isEmpty()`和`== `的区别,并总结了在处理null参数时的常见问题。实验证明,直接等于null会引发NullPointerException,而针对字符串的空检查应使用isEmpty()方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结论

等于 null 不能用

实验一

    public static void abc(String a){
        if (a.isEmpty()) System.out.println("empty");
        if (a == "") System.out.println("==''==");
        if (a == null) System.out.println("null");
    }

    @Test
    public void test(){
        String a = new String();
        String b = null;  
        String c = ""; 
        
        System.out.println("=======  a   ========");
        abc(a);
        System.out.println("========  b  =======");
        abc(b);
        System.out.println("=======  c  =========");
        abc(c);
    }

结果运行到 abc(b)时就报错了
在这里插入图片描述

于是

实验二

    public static void ac(String a){
        if (a.isEmpty()) System.out.println("empty");
        if (a == "") System.out.println("==''==");
        if (a == null) System.out.println("null");
    }

    public static void b(String a){
        if (a == "") System.out.println("==''==");
        if (a == null) System.out.println("null");
    }

    @Test
    public void test(){
        String a = new String();
        String b = null;
        String c = "";

        System.out.println("=======  a   ========");
        ac(a);
        System.out.println("========  b  =======");
        b(b);
        System.out.println("=======  c  =========");
        ac(c);
    }

运行结果如下:
在这里插入图片描述
显而易见, 等于 null 不能用

实验三【再次印证】

	String name = request.getParameter("aaa");
	System.out.println(name);
	if (name.isEmpty()) System.out.println("empty");
	if (name == "") System.out.println("==''==");
	if (name == null) System.out.println("null");

【说明:当参数不存在是,name为null】
当 参数aaa不存在时,同样报错java.lang.NullPointerException
当 参数aaa存在时, 无论为空还是不为空,不会报错!

结论

等于 null 不能用 isEmpty

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值