Java Code Example: If else Statement on boolean Expressions

Logical operators have different priorities and therefore are executed at different times.

The order is as follows:
Logical complements (!) are executed first,
logical conjunctions (&&) are executed next,
and logical disjunctions (||) are executed at the end.

Code Example

public class BooleanExpressions {
    public static void main(String[] args) {
        boolean a = true, b = false, c = true;

        if ((a || b) && c) {
            System.out.print("True");
        } else {
            System.out.print("False");
        }
    }
}

Output

True

Code Explanation

The code defines a Java class called BooleanExpressions with a single method, main(). The main() method evaluates the boolean expression (a || b) && c and outputs the result to the console.

The expression (a || b) && c uses the logical operators || (OR) and && (AND) to evaluate the values of the three boolean variables a, b, and c. The || operator returns true if either of the operands is true, and the && operator returns true only if both operands are true.

In this code, the values of a, b, and c are set to true, false, and true respectively. So, the expression (a || b) evaluates to true (since a is true), and the expression (a || b) && c evaluates to true (since both (a || b) and c are true).

As a result, the if statement outputs the message “True” to the console.