Home ยป Java Logical Operators Tutorial

Java Logical Operators Tutorial

In Java, logical operators are used to combine multiple boolean expressions or values to return a boolean result (true or false).

These operators play a crucial role in decision-making, control flow, and condition evaluation. Logical operators are primarily used with boolean (true/false) values, but they can also be applied to expressions that result in boolean values.

In this tutorial, we will cover:

1. Types of Logical Operators in Java

Java supports three logical operators:

  • AND (&&): Returns true if both operands are true.
  • OR (||): Returns true if at least one operand is true.
  • NOT (!): Inverts the boolean value of the operand.

These operators are used in conditional expressions, typically within control flow statements like if, while, and for loops.

2. AND Operator (&&)

The AND operator (&&) returns true only if both conditions are true. If either of the conditions is false, the result will be false.

Truth Table for &&:

A B A && B
true true true
true false false
false true false
false false false

Example 1: Using AND Operator

public class AndOperatorExample {
    public static void main(String[] args) {
        int x = 10;
        int y = 20;

        // Using && to check if both conditions are true
        if (x > 5 && y > 15) {
            System.out.println("Both conditions are true.");
        } else {
            System.out.println("At least one condition is false.");
        }

        // Checking multiple conditions
        boolean isStudent = true;
        boolean hasID = true;
        if (isStudent && hasID) {
            System.out.println("You can enter the library.");
        } else {
            System.out.println("You are not allowed to enter.");
        }
    }
}

Explanation:

  • In the first condition, both x > 5 and y > 15 are true, so the if block is executed.
  • In the second case, since both isStudent and hasID are true, the user is allowed to enter the library.

3. OR Operator (||)

The OR operator (||) returns true if at least one of the conditions is true. If both conditions are false, the result will be false.

Truth Table for ||:

A B A || B
false false false
false true true
true false true
true true true

Example 2: Using OR Operator

public class OrOperatorExample {
    public static void main(String[] args) {
        int x = 5;
        int y = 10;

        // Using || to check if at least one condition is true
        if (x > 10 || y > 5) {
            System.out.println("At least one condition is true.");
        } else {
            System.out.println("Both conditions are false.");
        }

        // Checking multiple conditions
        boolean isWeekend = true;
        boolean isHoliday = false;
        if (isWeekend || isHoliday) {
            System.out.println("You can relax today!");
        } else {
            System.out.println("It's a workday.");
        }
    }
}

Explanation:

  • In the first condition, x > 10 is false, but y > 5 is true, so the if block is executed.
  • In the second example, since isWeekend is true, the OR condition is satisfied, and the user can relax.

4. NOT Operator (!)

The NOT operator (!) inverts the boolean value of the operand. If the operand is true, it returns false, and vice versa.

Truth Table for !:

A !A
true false
false true

Example 3: Using NOT Operator

public class NotOperatorExample {
    public static void main(String[] args) {
        boolean isRaining = false;

        // Using ! to invert the boolean value
        if (!isRaining) {
            System.out.println("It's not raining, you can go outside.");
        } else {
            System.out.println("It's raining, better stay inside.");
        }

        boolean isLoggedIn = true;
        if (!isLoggedIn) {
            System.out.println("Please log in to continue.");
        } else {
            System.out.println("You are already logged in.");
        }
    }
}

Explanation:

  • In the first case, since isRaining is false, the !isRaining inverts it to true, and the user can go outside.
  • In the second case, isLoggedIn is true, so !isLoggedIn evaluates to false, meaning the user is already logged in.

5. Short-circuiting in Logical Operators

Java supports short-circuit evaluation for the && and || operators:

  • For &&: If the first condition is false, the second condition is not evaluated because the entire expression will be false.
  • For ||: If the first condition is true, the second condition is not evaluated because the entire expression will be true.

Example 4: Short-circuiting with AND Operator

public class ShortCircuitAndExample {
    public static void main(String[] args) {
        int x = 5;
        int y = 10;

        // Short-circuiting: the second condition is not evaluated because x > 10 is false
        if (x > 10 && y++ > 10) {
            System.out.println("Both conditions are true.");
        } else {
            System.out.println("At least one condition is false.");
        }

        // y will still be 10 because the second condition was not evaluated
        System.out.println("Value of y: " + y);  // 10
    }
}

Explanation:

  • The second condition y++ > 10 is not evaluated because the first condition x > 10 is false, and y remains unchanged.

Example 5: Short-circuiting with OR Operator

public class ShortCircuitOrExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 15;

        // Short-circuiting: the second condition is not checked because a < 10 is true
        if (a < 10 || b++ > 20) {
            System.out.println("At least one condition is true.");
        }

        // b will still be 15 because the second condition was not evaluated
        System.out.println("Value of b: " + b);  // 15
    }
}

Explanation:

  • Since a < 10 is true, the second condition b++ > 20 is not evaluated, and b remains 15.

6. Combining Logical Operators

You can combine multiple logical operators to create complex conditions.

Example 6: Combining AND, OR, and NOT Operators

public class CombineLogicalOperatorsExample {
    public static void main(String[] args) {
        int age = 18;
        boolean hasID = true;
        boolean isDrunk = false;

        // Combining &&, ||, and ! to evaluate complex conditions
        if (age >= 18 && hasID && !isDrunk) {
            System.out.println("You are allowed to enter the club.");
        } else {
            System.out.println("You are not allowed to enter the club.");
        }

        boolean isHoliday = true;
        boolean isWeekend = false;
        if (isHoliday || isWeekend) {
            System.out.println("You can relax today.");
        } else {
            System.out.println("It's a workday.");
        }
    }
}

Explanation:

  • The first condition checks if a person is of legal age, has an ID, and is not drunk. If all conditions are met, the person is allowed to enter the club.
  • The second condition checks if it's either a holiday or a weekend. If one of these conditions is true, the person can relax.

7. Key Considerations

  • Short-circuiting: Use short-circuiting to prevent unnecessary evaluations, especially if the second condition is expensive to evaluate.
  • Boolean Expressions: Logical operators are only applied to boolean values or expressions that return a boolean result.
  • Order of Evaluation: Parentheses can be used to enforce a specific evaluation order when combining multiple operators. For example:
if ((a > 5 && b < 10) || c == 20) {
    // Code
}

Conclusion

In this tutorial, we explored Java's logical operators:

  1. AND (&&): Returns true only if both operands are true.
  2. OR (||): Returns true if at least one operand is true.
  3. NOT (!): Inverts the boolean value.
  4. Short-circuiting: Stops evaluation as soon as the result is determined.
  5. Combining logical operators: Allows you to create complex conditions.

Understanding how logical operators work is essential for making decisions in your programs, especially when working with conditional statements.

You may also like