2021年3月7日星期日

Why && and || do not evaluate the rest of the expression, so method1() is not called for 2 and 4? [closed]

I get the wrong answer for this Java OCA practice question. The question is: What will be the output of the following program?

public class TestClass{    public static void main(String args[ ] ){      int i = 0 ;      boolean bool1 = true ;      boolean bool2 = false;      boolean bool  = false;      bool = ( bool2 &  method1(i++) ); //1      bool = ( bool2 && method1(i++) ); //2      bool = ( bool1 |  method1(i++) ); //3      bool = ( bool1 || method1(i++) ); //4      System.out.println(i);    }    public static boolean method1(int i){       return i>0 ? true : false;    }}  

My answer is 4, but the correct answer is 2. It says " && and || do not evaluate the rest of the expression, so method1() is not called for 2 and 4"; but why in the if statement, for example if(var1==true && var2==false), it evaluates for the rest of expression?

https://stackoverflow.com/questions/66523830/why-and-do-not-evaluate-the-rest-of-the-expression-so-method1-is-not-ca March 08, 2021 at 11:06AM

没有评论:

发表评论