Java中运算符“|”和“||”以及“&”和“&&”区别

1.“|”运算符:不论运算符左侧为true还是false,右侧语句都会进行判断,下面代码 public class TestOperator { private static int j = 0; private static Boolean method...

1.“|”运算符:不论运算符左侧为true还是false,右侧语句都会进行判断,下面代码

public class TestOperator {
	
	private static int j = 0;
	 
    private static Boolean methodB(int k) {
        j += k;
        return true;
    }
 
    public static void methodA(int i) {
        boolean b;
        b = i < 10 | methodB(4);
 
    }
 
    public static void main(String args[]) {
        methodA(0);
        System.out.println(j);
    }

}

 打印结果:4

2.“||”运算符:若运算符左边为true,则不再对运算符右侧进行运算,如下代码:

public class TestOperator {
	
	private static int j = 0;
	 
    private static Boolean methodB(int k) {
        j += k;
        return true;
    }
 
    public static void methodA(int i) {
        boolean b;
        b = i < 10 | methodB(4);
        b = i < 10 || methodB(8);
 
    }
 
    public static void main(String args[]) {
        methodA(0);
        System.out.println(j);
    }

}

 打印结果:4,说明“||”运算,左边为true后就不会再执行右边,而“|”运算,左边为true后依然会执行右边。

3.&运算符与|运算符类似:不论运算符左侧为true还是false,右侧语句都会进行判断:

public class TestOperator {
	
	private static int j = 0;
	 
    private static Boolean methodB(int k) {
        j += k;
        return true;
    }
 
    public static void methodA(int i) {
        boolean b;
        b = i > 10 & methodB(4);
 
    }
 
    public static void main(String args[]) {
        methodA(0);
        System.out.println(j);
    }

}

 打印结果:4,说明&运算符左侧为false,单依然会运行右侧语句。

4.“&&”运算符与“||”运算符类似:若运算符左侧为false则不再对右侧语句进行判断:

public class TestOperator {
	
	private static int j = 0;
	 
    private static Boolean methodB(int k) {
        j += k;
        return true;
    }
 
    public static void methodA(int i) {
        boolean b;
        b = i > 10 & methodB(4);
        b = i > 10 && methodB(8);
 
    }
 
    public static void main(String args[]) {
        methodA(0);
        System.out.println(j);
    }

}

 打印结果:4,说明&&运算符左侧为false则不再对右侧语句

原文出处:http://ninghq.iteye.com/blog/2431926

  • 发表于 2018-10-10 23:39
  • 阅读 ( 369 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除