Java逻辑运算符

Java逻辑运算符有:||(逻辑或),&&(逻辑与),!(逻辑非)。当两个操作数均为布尔类型时,|(按位或)和&(按位与)也可当逻辑运算符使用。

  • ||(逻辑或)
    只有两个操作数全为false才返回false,其余都返回true。若第一个操作数为true则直接返回结果true,后面部分不会运行。
    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    	    boolean op1 = true,result;
    	    int op3 = 1;
    	    result = op1 || (++op3 == 2);
    	    System.out.println("result的值:"+result);
    	    System.out.println("op3的值:"+op3);
    	}
    result的值:true
    op3的值:1

    如上图,由于op1为true所以操作符后半部分没运行,op3没自增,依旧为1。

  • |(按位或)
    只有两个操作数全为false才返回false,其余都返回true。若第一个操作数为true,依旧要运行后半部分。
    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    	    boolean op1 = true,result;
    	    int op3 = 1;
    	    result = op1 | (++op3 == 2);
    	    System.out.println("result的值:"+result);
    	    System.out.println("op3的值:"+op3);
    	}
    result的值:true
    op3的值:2
    

    如上图,虽然op1为true,依旧会运行操作符的后半部分,op3自增,所以为2。

  • &&(逻辑与)
    只有两个操作数全为true才返回true,其余都返回false。若第一个操作数为false则后半部分不会运行。
    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    	    boolean op1 = false,result;
    	    int op3 = 1;
    	    result = op1 && (++op3 == 2);
    	    System.out.println("result的值:"+result);
    	    System.out.println("op3的值:"+op3);
    	}
    result的值:false
    op3的值:1

     

  • &(按位与)
    只有两个操作数全为true才返回true,其余都返回false。若第一个操作数为false则后半部分依旧会运行。
    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    	    boolean op1 = false,result;
    	    int op3 = 1;
    	    result = op1 & (++op3 == 2);
    	    System.out.println("result的值:"+result);
    	    System.out.println("op3的值:"+op3);
    	}
    result的值:false
    op3的值:2

     

注意:

  • 当操作数为整型等类型时,|和&为位操作符。链接:Java位运算符

参考:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值