# Expression Evaluation with && and || operators

Anant Jahagirdar
Greenhorn
Posts: 3
Hi,
I am getting confused with the following example. Eventhough && has higher precedence the expression is evaluated differently. Please explain me.
class Test {
static boolean ant(){
System.out.println("within method");
return true;
}
public static void main(String[] args) {
boolean a , b, c;
a=b=c=false;
System.out.println((a=true) || (b= ant()) && (c=true));
System.out.println(a+ "," + b+"," +c);
}
}
out put is : true
true, false, false

William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
Your clause (a = true) sets variable a to true and returns true. The || (short circuit or) sees true and does not evaluate the remainder. Remember, left to right evaluation.
Bill

Anant Jahagirdar
Greenhorn
Posts: 3
Hi
When the Precedence comes in to picure while using && and || operators?

Jose Botella
Ranch Hand
Posts: 2120
Welcome to the Ranch Anant.
I have not been able to observe the evaluation of the right operand to && before its left one in any example I made up. Otherwise the short-circuit operators could not short-circuit.

William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
The short circuit behavior of && is to quit if the left operand is false - since the result can't possibly be anything but false. Therefore to see the right operand evaluated you must have a true result on the left.
Bill

Jose Botella
Ranch Hand
Posts: 2120
Anant, this code shows, at least, that the && operator has a bigger precedence than =

a) v is evaluated to false
b) true is evaluated to true
c) the precedence of = is compared with &&. Thus = is not carried out but instead...
d) m() is evaluated and false is printed
e) && is performed yielding true
f) now the previously obtained true is assigned to v and printed.
[ January 10, 2003: Message edited by: Jose Botella ]

Anant Jahagirdar
Greenhorn
Posts: 3
Thanks all for your detailed answers. When short circuit operators are in the expression, the left operand is evaluated first and then if operator is || and evalated operand is true, the expression evaluation process stops. same thing happens for && with false operand.Is this correct?