1

Logical AND && has higher precedence than logical OR ||.

This is simple java code http://ideone.com/KWUOla

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        if( A() || B() && C() && D() ){
            System.out.println("done...");
        }
    }
    public static boolean A(){
        System.out.println("This is class A");
        return true;
    }
    public static boolean B(){
        System.out.println("This is class B");
        return true;
    }
    public static boolean C(){
        System.out.println("This is class C");
        return true;
    }
    public static boolean D(){
        System.out.println("This is class D");
        return true;
    }    
}

In this program function A() is completing first then OR is evaluated and since the left operand is true the if condition is satisfied.

But as per the precedence table all logical AND && should be evaluated before the evaluation of logical OR ||.

Does Java have the same priority for logical AND && and logical OR ||? If not, please clarify the precedence order between logical AND && and logical OR ||.

Zong
  • 6,160
  • 5
  • 32
  • 46
achilles7
  • 23
  • 2
  • 4
    Don't confuse precedence with associativity. – awksp Jul 07 '14 at 04:08
  • 1
    Don't be parentheses averse the compiler will optimize regardless. – Cheruvian Jul 07 '14 at 04:10
  • 1
    Also, [running this myself](http://ideone.com/SslQYc) just shows `This is class A`, then `done...`. Strange. Not sure how you got your result... – awksp Jul 07 '14 at 04:11
  • 1
    Think of ```&&``` and ```||``` like ```*``` and ```+```. ```a + b * c * d = a + (b * c * d)```. But since you're using methods, remember that logical operators short circuit as soon as the result is known, so both ```false && foo()``` and ```true || foo()``` never call ```foo```. – David Ehrmann Jul 07 '14 at 04:12
  • associativity is order of execution (either from left to right or from right to left) of same operator. But If we have operator of higher precedence in expression then operator having higher precedence should be evaluated first. Here logical And(&&) have higher precedence but it is not evaluated first. – achilles7 Jul 07 '14 at 04:15
  • You're still confusing precedence with associativity. Precedence affects grouping. Things are still evaluated from left to right. – awksp Jul 07 '14 at 04:16

2 Answers2

4

The precedence rules remove the ambiguity by effectively adding brackets:

A() || ((B() && C()) && D())

And brackets don't affect the order of execution which is always left to right.

Then as you say, it doesn't need to calculate the right hand side of the or as the left hand side is true. (This is called short circuiting).

weston
  • 54,145
  • 21
  • 145
  • 203
0

It runs only A() because it returns true. I strongly recommend to use parenthesises.

bestalign
  • 227
  • 1
  • 9