加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

说说 & 和 && 还有 | 和 | | 的区别

发布时间:2020-12-15 08:25:14 所属栏目:Java 来源:网络整理
导读:和都可以用作逻辑与的运算符,为短路与运算,不是短路与运算。 另外可以做为整数的位运算符的与运算。 ? 例1: String str = null ; if (str != null !str.equals("" )) { System.out.println( "测试" ); } 对于 if (str != null !str.equals("" )) 表达式,

&和&&都可以用作逻辑与的运算符,&&为短路与运算,&不是短路与运算。

另外&可以做为整数的位运算符的与运算。

?

例1:

String str = null;
        if (str != null && !str.equals("")) {
            System.out.println("测试");
        }

对于 if (str != null && !str.equals(""))表达式,当str为null的时,后面的表达式不会执行,说明已经短路,所以不会出现java.lang.NullPointerException,已经短路了,如果将&&改为&,则会抛出异常。当然不建议这样的写法,应该写为if (str != null && !“”.equals(str))

&&运算符,短路的情况是左边的执行错误的情总下,不执行右边的了,直接执行else里面的东西

例2:

?

public static void main(String[] args) {
        int x = 33;
        int y = 1;
        if (x == 33 && ++y>0) {
            System.out.println(x + "," + y);
        }
    }
public static void main(String[] args) {
        int x = 33;
        int y = 1;
        if (x == 33 & ++y>0) {
            System.out.println(x + "," + y);
        }
    }

y都会增长

如果变成:

?

public static void main(String[] args) {
        int x = 33;
        int y = 1;
        if (x != 33 && ++y>0) {
            System.out.println(x + "," + y);
        }else {
     System.out.println(x + "," + y);
     } }

?运行结果:

y就不会增长了,因为只运行了左边拉判断,再左边拉判断为空的时候,右边的判断直接不用执行了。

?

|和| | 的情况和 & 和 && 的情况一样,把上面的符号替换一下就行了。

细节决定成败!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读