Just wondering if parentheses have higher precedence than logical operators in a boolean expression in java.
For example: Is (x > 0 || x < 10) && y < 0 the same as (x > 0 || (x < 10 && y < 0))?
(edited format)
Just wondering if parentheses have higher precedence than logical operators in a boolean expression in java.
For example: Is (x > 0 || x < 10) && y < 0 the same as (x > 0 || (x < 10 && y < 0))?
(edited format)
Yes, they have. It's like adding parenthesis on a math operation to separate in terms. The examples you provide are NOT the same.
In the first one you are saying: if any of these conditions are true AND this other conditions is true→then return true. Meaning that the second condition always has to be true.
In the second one you are saying: If the first condition is true OR both this other condition are true→ then return true. This means that if the first condition is true, you don't care about the rest.
Let's say we plug in a value of 1 for X and a value of 2 for Y. The first one will return false because Y has to be smaller than 2 regardless of the X value. The second case however, will return true. Since X is greater than 0 then it will return true as it doesn't care about the rest because it's an OR gate.
The presence of brackets within logical conditions do not change the precedence of your condition, as boolean operations will always execute from left to right.
Brackets can be used to "group" sub-conditions that are used in a larger expression but the presence of these will not give any priority to their execution. See the below example:
class Scratch {
public static void main(String[] args) {
if (f() || (t() && f())){
System.out.println("finish");
}
}
public static boolean f() {
System.out.println("false");
return false;
}
public static boolean t() {
System.out.println("true");
return true;
}
}
This will output:
false
true
false
As this corresponds to the left to right order of execution. Note that if the first entry to an OR function is true (Using t()
in my example code) then the latter condition isn't even evaluated as the OR condition has already been satisfied.