&&和||放在一个表达式中是怎么执行的?

先上代码:

public class Test {
	
	public static void main(String[] args) {
		
		if(test1() && test2() || test3()) {
			System.out.println("Main: Result is true!");
		}else {
			System.out.println("Main: Result is false!");
		}
		
	}
	
	private static boolean test1() {
		
		System.out.println("This is test1!");
		
		return false;
	}
	
	private static boolean test2() {
		
		System.out.println("This is test2!");
		
		return true;
	}
	
	private static boolean test3() {
		
		System.out.println("This is test3!");
		
		return true;
	}
}

运行结果为:

This is test1!
This is test3!
Main: Result is true!

分析:

上面这个表达式中涉及的操作符的优化级是一样的,按照从左到右的原则:
(1)test1() && test2()先运算,由于test1() 是false,按照&&的短路原则,表达式 test2()就不用执行了,因为已经不影响结果了
(2)test1() && test2() 的运算结果是fale,再一看,后面的运算符是||,要想得到整体表达式的结果,||后面的表达式仍然需要运算,执行test3(),结果是true按照||操作符的原则,false||test3()的结果是true.

自我总结:

对于该表达式来说,可以拆分成test1() && test2()先进行运算,它们的结果再与test3()运算。比如判断年份是否为闰年时,满足闰年的条件为year % 4 == 0 && year % 100 == 0 或者 year % 400 == 0,此时我们就可以这两种情况用 || 连接起来。看似复杂,其实都是从左到右依次计算,这就相当于把三个条件拆分成两种情况,当第一种情况不满足时,才会计算第二种情况。

你可能感兴趣的:(java)