-2

Say a condition looks something like this:

    if (false && true)
      //Code

would it break away from the condition before it reaches the true, because a false and && would never be true?

Also, if you have code like this:

    boolean dividesToTwo (int operand1, int operand2) {
      if ((operand2 != 0) && operand1 / operand2 == 2)
        return true;
      return false;
    }

would it successfully work as intended, or would you get an error for division by zero? (if the second operand is a zero)

Zach Brantmeier
  • 716
  • 3
  • 8
  • 23

3 Answers3

3

For your first part of the question see this answer. This is called short circuit evaluation:

  • when using && the second part is only evaluated if the first part is true
  • when using || the second part is only evaluated if the first part is false

For your second part of the question:

Yes this will work as expected! If operand2 is zero the evaluation is canceled and no division by zero will occurr!

Community
  • 1
  • 1
ultimate
  • 653
  • 5
  • 18
1

Yes, if (false && true) is evaluated, on seeing false, the condition would stop being evaluated from there (i.e before it reaches true)

However if it was an OR (||) operation, it wouldve have to check the second part before determining it was true or false.

For your second question, it would run as per expected. No division of zero would occur.

Prasanth Louis
  • 4,658
  • 2
  • 34
  • 47
0
  if ((operand2 != 0) && operand1 / operand2 == 2)

That means if operand2!=0 then only division happens because of behavior of &&.If the first half is true, then only second half executes. If first half is false, then there will be no execution of second half.

Read how && behaves

in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression:

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307