JAVA_逻辑与 & 位与的区别

有些项目中遇到一些返回为boolean类型的方法,有些使用逻辑与 ||,有些使用位与操作符 |, 因此做个记录。

区别在于 逻辑与 碰到有true 则会返回,位与 会执行完表达式

1. 逻辑与表达式:   boolean value = method1() || method2() || method3 (); 

 则如果 method1() 返回值为true , method2() 和 method3 则不会再执行; 如果method1() 返回值为false, 则会执行method2(); 如果method2()返回为true, 则method3()不会被执行,如此类推。

2. 位与表达式: boolean value = method1() | method2() | method3 (); 

则不管method()1 / method2() 的返回值是多少,这三个函数都会被执行。

所以,按照实际需要使用。

3. 例子

(敲代码验证最好)

package com.example.javatest.booleancheck;

public class BooleanTest {
    public static void main(String[] args) {
        System.out.println("=====main start=====");
        BooleanTest booleanTest = new BooleanTest();
        System.out.println("shouldUpdateState=" + booleanTest.shouldUpdateState());
        System.out.println("=====main end=====");
    }

    private boolean shouldUpdateState() {
        return updateLeft() || updateRight() || updateUp() || updateDown();
        //return updateLeft() | updateRight() | updateUp() | updateDown();
    }

    private boolean updateLeft() {
        System.out.println("=====updateLeft=====");
        return true;
    }

    private boolean updateRight() {
        System.out.println("=====updateRight=====");
        return true;
    }

    private boolean updateUp() {
        System.out.println("=====updateUp=====");
        return true;
    }

    private boolean updateDown() {
        System.out.println("=====updateDown=====");
        return true;
    }
}

shouldUpdateState() 是最终返回的结果, 它可以由逻辑与 / 位与 操作实现。 updateleft..等四个方法都返回true

(1) 使用逻辑与操作符 (return updateLeft() || updateRight() || updateUp() || updateDown();), 则输出结果为:

> Task :javatest:BooleanTest.main()
=====main start=====
=====updateLeft=====
shouldUpdateState=true
=====main end=====

(2)使用位与操作符 (return updateLeft() | updateRight() | updateUp() | updateDown();), 则输出结果为:

> Task :javatest:BooleanTest.main()

=====main start=====
=====updateLeft=====
=====updateRight=====
=====updateUp=====
=====updateDown=====

shouldUpdateState=true
=====main end=====

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值