How a given if condition is giving true in java

  • A+
Category:Languages

I am unable to understand why following if blocks execute. How the if conditions will be evaluated?

public class Test {     public static void main(String[] args)     {         if (true || (false ||  true) && false)         {             System.out.println("How does this condition becomes true.");         }          if (false && (false ||  true) || true)         {             System.out.println("Same with this condition, why is it true.");         }     } } 

 


&& has higher precedence than || (source). So adding in parens to emphasize how those are being evaluated:

    if (true || ((false ||  true) && false)) // -------------^-------------------------^ 

and

    if ((false && (false ||  true)) || true) // -----^-------------------------^ 

As you can see, you end up with x || y where x is true in the first example, and y is true in the second example. Naturally both true || false and false || true are true.

You can see it in action by using a method that outputs what it's doing (live copy) (remember that both || and && short-circuit, meaning they don't evaluate operands that cannot change the result):

public class Test {     private static boolean b(String label, boolean value) {         System.out.println(label + ": " + value);         return value;     }     public static void main(String[] args)     {         if (b("1", true) || (b("2", false) || b("3", true)) && b("4", false))         {             System.out.println("How does this condition becomes true.");         }          if (b("5", false) && (b("6", false) || b("7", true)) || b("8", true))         {             System.out.println("Same with this condition, why is it true.");         }     } } 

When run, that outputs:

 1: true How does this condition becomes true. 5: false 8: true Same with this condition, why is it true. 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: