資策會|JAVA|邏輯運算子之短路運算

短路運算

這是上課時有提到的,今天就來來驗證看看。

邏輯運算子

短路運算 : ||  (or) , &&(and)
非短路運算 :  |  (or) , &(and)

測試

拿or來測試囉!


                int i = 10;
int j = 20;
if((i+=20)==30 || (j+=20) == 40 ) {
System.out.println(i);
System.out.println(j);
}
int x = 10;
int y = 20;
if((x+=20)==30 | (y+=20) == 40 ) {
System.out.println(x);
System.out.println(y);
}

印出後的結果是!!!!
30
20
30
40

拿and來測試囉!

                int i = 10;
int j = 20;
if(!((i+=20)==40000 && (j+=20) == 40 )) {
System.out.println(i);
System.out.println(j);
}
int x = 10;
int y = 20;
if(!((x+=20)==40000 & (y+=20) == 40 )) {
System.out.println(x);
System.out.println(y);

}

印出後的結果是!!!!
30
20
30
40

小結

這驗證了短路運算下只要判斷是符合了所需條件,就會直接往下執行啦!
而非短路運算則是會全部執行判斷完後,才會執行!



留言