逻辑运算符中"&"与"&&"和"|"与"||"的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35654259/article/details/84180084

“&”和“&&”的区别:

单&时,左边无论真假,右边都进行运算;

双&时,如果左边为真,右边参与运算,如果左边为假,那么右边不参与运算;

​
class OperatorDemo {
	public static void main(String[] args) {

		int x = 3;
		int y = 4;
		
		/*
                &&和&的区别:
		A:最终结果一样。
		B:&&具有短路效果。左边是false,右边不执行。
                */
		//boolean b1 = ((++x == 3) & (y++ == 4)); //运行完后 x== 4 y == 5
		boolean b1 = ((++x == 3) && (y++ == 4));  //运行完后 x== 4 y == 4
		System.out.println("x:"+x);
		System.out.println("y:"+y);
		System.out.println(b1);
	}
}

​

“|”和“||”的区别

单|时,左边无论真假,右边都进行运算;

双|时,如果左边为假,右边参与运算,如果左边为真,那么右边不参与运算;

​
class OperatorDemo {
	public static void main(String[] args) {

		int x = 3;
		int y = 4;
		
		/*
                ||和|的区别:
		A:最终结果一样。
		B:&&具有短路效果。左边是true,右边不执行。
                */
		//boolean b1 = ((++x == 4) | (y++ == 4)); //运行完后 x== 4 y == 5
		boolean b1 = ((++x == 4) || (y++ == 4));  //运行完后 x== 4 y == 4
		System.out.println("x:"+x);
		System.out.println("y:"+y);
		System.out.println(b1);
	}
}

​

猜你喜欢

转载自blog.csdn.net/qq_35654259/article/details/84180084
今日推荐