Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with the short circuit logic in this Java code?

Why doesn't func3 get executed in the program below? After func1, func2 doesn't need to get evaluated but for func3, shouldn't it?

if (func1() || func2() && func3()) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}

public static boolean func1() {
    System.out.println("func1");
    return true;
}

public static boolean func2() {
    System.out.println("func2");
    return false;
}

public static boolean func3() {
    System.out.println("func3");
    return false;
}
like image 313
Sajal Dutta Avatar asked May 12 '09 13:05

Sajal Dutta


2 Answers

You're using a short-circuited or. If the first argument is true, the entire expression is true.

It might help if I add the implicit parentheses that the compiler uses

Edit: As Chris Jester-Young noted, this is actually because logical operators have to left-to-right associativity:

if (func1() || (func2() && func3()))

After func1 returns, it becomes this:

if (true || (func2() && func3()))

After evaluating the short-circuited or, it becomes:

if (true)
like image 79
Powerlord Avatar answered Oct 19 '22 05:10

Powerlord


Java functions are evaluated according to precedence rules

because "&&" is of higher precendence than "||", it is evaluated first because you did not have any brackets to set explicit precedence

so you expression of

(A || B && C) 

which is

(T || F && F)

is bracketed as

(T || (F && F)) 

because of the precedence rules.

Since the compiler understands that if 'A == true' it doesn't need to bother evaluating the rest of the expression, it stops after evaluating A.

If you had bracketed ((A || B) && C) Then it would evaluate to false.

EDIT

Another way, as mentioned by other posters is to use "|" and "&" instead of "||" and "&&" because that stops the expression from shortcutting. However, because of the precedence rules, the end result will still be the same.

like image 41
DevinB Avatar answered Oct 19 '22 06:10

DevinB