How does the Java if statement work when it has the assignment and equality check of OR-d together?

Why does this if statement, with assignment and equality checking, evaluate to false?

public static void test() { boolean test1 = true; if (test1 = false || test1 == false) { System.out.println("Yes"); } else { System.out.println("No"); } } 

Why is this seal No ?

+8
java
source share
4 answers

Due to operator priority . This is equivalent to this:

 boolean test1 = true; if (test1 = (false || test1 == false)) { ... } 

The part in parentheses evaluates to false .

+14
source share

you assign a value to the var in if statement, but you do not use it. If you want to assign an if statement and use it, you can do this:

 boolean test1; if ((test1 = false) == true) { System.out.println("Yes"); } else { System.out.println("No"); } 
-one
source share

Your if has the following statements that take precedence as follows: equality> logical OR> assignment

Then it goes down like this:

 (test1 = false || test1 == false) //substituing test1 with its value (test1 = false || true == false) //evaluating equality (test1 = false || false) //evaluating logical OR (test1 = false) //evaluating assignment (test1) //substituing test1 with its value (false) //evaluating primitive value, going to else block 

Consequently, seal No.

-one
source share

The result of this code will print “no,” because you assign test1 to false test1 = false the if statement then evaluates to false, because then you evaluate to test1 == false and another block executes

This may be what you are looking for:

  if ((test1 == false) || (test1 == false)) //this line if the first answer is true it returns true without checking the seconded statement. // if (test1 == false) would be the, same elauates as true { System.out.println("Yes"); } else { System.out.println("No"); } 

Look for a short circuit or an operator, this can help you better understand the problem.

-2
source share

All Articles