在条件表达式中null.equals(str)和str.equals(null)类似形式的区别

package test1;

public class javatest1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str="123";
        String str1=null;
        //str-test
        if("123"==str)
        {
            System.out.println("the result of judge is true");
        }
        else
        {
            System.out.println("the result of judge is false");
        }
        if(str=="123")
        {
            System.out.println("the result of judge is true");
        }
        else
        {
            System.out.println("the result of judge is false");
        }
        
        //str1-test
        if("123".equals(str1))
        {
            System.out.println("the result1 of judge is true");
        }
        else
        {
            System.out.println("the result1 of judge is false");
        }
        //通过debug模式调试,在此处遇到了空指针错误
        if(str1.equals("123"))
        {
            System.out.println("the result1 of judge is true");
        }
        else
        {        
            System.out.println("the result1 of judge is false");
        }
    }

}


先看以上实例,运行结果:

显然在str1为空的时候,操作str1.equals("123")出现了空指针异常。所以就是为什么在很多编程实例中的写法都是把表达式中的常量放在前面,把变量放在后面的原因,就是为了避免出现这种空指针异常,特别是在web开发中,不同的页面之间的传值,如果不采用这种写法,就可能导致空指针异常,继而可能导致,页面直接崩溃的结果。基于这种情况,这种常量在前,变量在后的写法也就成为了一种编程的规范。

即应该写成:"123".equals(str1)

 


————————————————
版权声明:本文为CSDN博主「hymKing」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hymking/article/details/8849844

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值