Popular Searches
Popular Course Categories
Popular Courses

Understanding Logical Operators

Understanding Logical Operators

Operators and Expressions in Java

Understanding Logical Operators in Java

Course: Core Java Training

Topic: Understanding Logical Operators in Java

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Logical Operators in Java

Logical operators are used to combine, reverse, or evaluate Boolean expressions in Java. They help a program make decisions by checking whether one or more conditions are true or false.

Logical operators are commonly used in conditional statements such as if, if-else, and switch guards, as well as in loops such as while and for. They are useful for validating user input, checking eligibility, verifying login details, controlling application workflows, and evaluating business rules.

For example, an application might allow a user to access a service only when the user is logged in and the account is active. This requires evaluating multiple conditions together.

boolean isLoggedIn = true;
boolean isAccountActive = true;

if (isLoggedIn && isAccountActive) {
    System.out.println("Access granted.");
}

Output:

Access granted.

2. Learning Objectives

  • Understand the purpose of logical operators in Java.
  • Learn the difference between logical AND, logical OR, and logical NOT.
  • Understand short-circuit evaluation.
  • Differentiate between && and &, and between || and |.
  • Use logical operators with comparison operators and Boolean variables.
  • Apply operator precedence and parentheses correctly.
  • Write conditional expressions for practical programming scenarios.
  • Identify common logical errors and test Boolean expressions effectively.

3. What Are Logical Operators?

Logical operators evaluate Boolean values or expressions and produce a Boolean result. In Java, the primitive Boolean type has two possible values: true and false.

The three fundamental logical operators are:

Operator Name Purpose Example
&& Logical AND True only when both operands are true; uses short-circuit evaluation. a && b
|| Logical OR True when at least one operand is true; uses short-circuit evaluation. a || b
! Logical NOT Reverses a Boolean value. !a

4. Logical AND Operator (&&)

The logical AND operator, written as &&, returns true only when both Boolean operands are true. If the first operand evaluates to false, Java does not evaluate the second operand.

Truth Table for Logical AND

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

Example: Logical AND

public class LogicalAndExample {
    public static void main(String[] args) {
        int age = 25;
        boolean hasLicense = true;

        if (age >= 18 && hasLicense) {
            System.out.println("Eligible to drive.");
        } else {
            System.out.println("Not eligible to drive.");
        }
    }
}

Output:

Eligible to drive.

Explanation

  • age >= 18 evaluates to true.
  • hasLicense is true.
  • Both conditions are true, so the complete AND expression is true.
  • The first branch of the if statement executes.

Practical Uses of AND

  • Checking whether a user is logged in and an account is active.
  • Checking whether a number falls within a specified range.
  • Validating that required form fields are completed.
  • Ensuring a person meets multiple eligibility conditions.

5. Logical OR Operator (||)

The logical OR operator, written as ||, returns true when at least one operand is true. It returns false only when both operands are false.

Java evaluates the second operand only when the first operand evaluates to false.

Truth Table for Logical OR

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

Example: Logical OR

public class LogicalOrExample {
    public static void main(String[] args) {
        boolean hasEmail = false;
        boolean hasPhone = true;

        if (hasEmail || hasPhone) {
            System.out.println("Contact information is available.");
        } else {
            System.out.println("No contact information available.");
        }
    }
}

Output:

Contact information is available.

Explanation

  • hasEmail is false.
  • hasPhone is true.
  • At least one condition is true, so the OR expression returns true.
  • The first branch of the if statement executes.

Practical Uses of OR

  • Allowing login with either an email address or a phone number.
  • Checking whether a user has administrator or manager permissions.
  • Accepting multiple valid choices or conditions.
  • Determining whether a number is below a minimum or above a maximum limit.

6. Logical NOT Operator (!)

The logical NOT operator, written as !, reverses a Boolean value. If a condition is true, applying NOT makes it false. If the condition is false, applying NOT makes it true.

Truth Table for Logical NOT

Condition A !A
false true
true false

Example: Logical NOT

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

        if (!isRaining) {
            System.out.println("You can plan an outdoor activity.");
        } else {
            System.out.println("Consider an indoor activity.");
        }
    }
}

Output:

You can plan an outdoor activity.

Explanation

The variable isRaining is false. The expression !isRaining therefore evaluates to true, so the first branch executes.

Common Uses of NOT

  • Checking whether a user is not logged in.
  • Testing whether a collection is not empty.
  • Reversing a Boolean flag.
  • Executing code when a condition is false.

7. Difference Between && and &

Java supports both logical AND (&&) and Boolean AND (&). When both operands are Boolean, both operators produce an AND result, but their evaluation behavior differs.

Feature && &
Common Boolean use Logical AND Boolean AND
Short-circuit behavior Yes No
Evaluates second operand when first is false No Yes
Can operate on integer bit patterns No Yes, as a bitwise AND operator
Typical conditional usage Preferred when short-circuiting is useful Used when evaluating both Boolean operands is intended

Example: Short-Circuit AND

public class ShortCircuitAnd {
    public static void main(String[] args) {
        int number = 10;

        if (number < 5 && number / 0 > 1) {
            System.out.println("Condition is true.");
        } else {
            System.out.println("Condition is false.");
        }
    }
}

Output:

Condition is false.

The first condition is false, so the second operand is not evaluated. Consequently, division by zero is avoided in this example.

Using Single &

boolean first = false;
boolean second = (10 / 0 > 1);

// This throws ArithmeticException while evaluating second,
// before the & expression can be evaluated.

For a direct comparison of evaluation behavior, consider this example:

public class AndEvaluation {
    static boolean checkSecond() {
        System.out.println("Second condition evaluated.");
        return true;
    }

    public static void main(String[] args) {
        boolean a = false;

        System.out.println(a && checkSecond());
        System.out.println(a & checkSecond());
    }
}

Output:

false
Second condition evaluated.
false

The first expression skips checkSecond(). The second expression evaluates it because single & does not short-circuit Boolean operands.

8. Difference Between || and |

Java also provides logical OR (||) and Boolean OR (|). Both produce an OR result when used with Boolean operands, but they differ in evaluation behavior.

Feature || |
Boolean operation Logical OR Boolean OR
Short-circuit behavior Yes No
Evaluates second operand when first is true No Yes
Can operate on integer bit patterns No Yes, as a bitwise OR operator

Example: Short-Circuit OR

public class ShortCircuitOr {
    static boolean checkSecond() {
        System.out.println("Second condition evaluated.");
        return false;
    }

    public static void main(String[] args) {
        boolean first = true;

        System.out.println(first || checkSecond());
        System.out.println(first | checkSecond());
    }
}

Output:

true
Second condition evaluated.
true

With ||, the second method is not called because the first operand is already true. With Boolean |, both operands are evaluated.

9. Understanding Short-Circuit Evaluation

Short-circuit evaluation means Java evaluates only as much of a logical expression as necessary to determine the result.

  • For A && B, if A is false, the entire expression must be false, so B is skipped.
  • For A || B, if A is true, the entire expression must be true, so B is skipped.
  • For !A, Java evaluates A and reverses its Boolean result.

Example: Safe Null Check

public class NullCheckExample {
    public static void main(String[] args) {
        String name = null;

        if (name != null && name.length() > 0) {
            System.out.println("Name is available.");
        } else {
            System.out.println("Name is missing or empty.");
        }
    }
}

Output:

Name is missing or empty.

Since name != null is false, Java skips the call to name.length(). This avoids a NullPointerException.

Best practice: Put the safety check first when the second condition depends on the first condition being true.

10. Combining Logical Operators with Comparison Operators

Logical operators are often combined with comparison operators such as ==, !=, >, <, >=, and <=.

Example: Checking a Number Range

public class RangeCheck {
    public static void main(String[] args) {
        int number = 25;

        if (number >= 10 && number <= 50) {
            System.out.println("Number is within the range.");
        } else {
            System.out.println("Number is outside the range.");
        }
    }
}

Output:

Number is within the range.

Example: Checking Multiple Choices

public class ChoiceCheck {
    public static void main(String[] args) {
        int day = 6;

        if (day == 6 || day == 7) {
            System.out.println("It is the weekend.");
        } else {
            System.out.println("It is a weekday.");
        }
    }
}

Output:

It is the weekend.

11. Operator Precedence and Parentheses

Operator precedence determines how Java groups parts of an expression when parentheses are not used. In general, logical NOT (!) has higher precedence than logical AND (&&), which has higher precedence than logical OR (||).

For example:

boolean a = true;
boolean b = false;
boolean c = true;

boolean result = a || b && c;

The expression is evaluated as:

boolean result = a || (b && c);

Since b && c is false and a is true, the result is true.

Example with Parentheses

int age = 20;
boolean hasPermission = false;
boolean result = (age >= 18 && hasPermission) || age >= 21;

System.out.println(result);

Output:

false

Parentheses make the intended grouping easier to read. Even when parentheses are not strictly required, they are useful for complicated conditions.

12. Logical Operators in if-else Statements

Logical operators help a program select a path based on multiple conditions.

public class LoginValidation {
    public static void main(String[] args) {
        boolean usernameCorrect = true;
        boolean passwordCorrect = true;
        boolean accountLocked = false;

        if (usernameCorrect && passwordCorrect && !accountLocked) {
            System.out.println("Login successful.");
        } else {
            System.out.println("Login failed.");
        }
    }
}

Output:

Login successful.

The expression requires both credentials to be correct and the account not to be locked. All three requirements must be satisfied for the login condition to be true. In a real application, authentication should be performed securely on the server side rather than relying only on client-side Boolean flags.

13. Logical Operators in Loops

Logical operators can be used in loop conditions to control repetition. A loop continues while its condition evaluates to true.

Example: While Loop

public class WhileLogicalExample {
    public static void main(String[] args) {
        int number = 1;

        while (number <= 5 && number > 0) {
            System.out.println(number);
            number++;
        }
    }
}

Output:

1
2
3
4
5

The loop continues while the number is at most five and greater than zero.

Example: for Loop

public class ForLogicalExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10 && i % 2 == 0; i++) {
            System.out.println(i);
        }
    }
}

This example prints nothing because the initial value of i is 1, so the condition i % 2 == 0 is false from the beginning. This illustrates why the initial state and all parts of a compound loop condition must be checked carefully.

14. De Morgan's Laws

De Morgan's laws describe how logical NOT interacts with AND and OR. They are useful when simplifying conditions or understanding the opposite of a compound expression.

Original Expression Equivalent Expression
!(A && B) !A || !B
!(A || B) !A && !B

Example

boolean hasTicket = true;
boolean hasId = false;

boolean condition1 = !(hasTicket && hasId);
boolean condition2 = !hasTicket || !hasId;

System.out.println(condition1);
System.out.println(condition2);

Output:

true
true

Both expressions are equivalent. Since the person does not have both a ticket and an ID, the negation of that combined condition is true.

15. Common Logical Operator Mistakes

Mistake Why It Is Incorrect or Risky Correct Approach
Using & instead of && The second operand is evaluated even if the first is false. Use && when short-circuit behavior is intended.
Using | instead of || The second operand is evaluated even if the first is true. Use || when short-circuit behavior is intended.
Incorrect range check: x > 10 && x < 5 A value cannot satisfy both comparisons at once. Review the intended minimum and maximum limits.
Using assignment where comparison is intended Java does not allow assigning a Boolean expression with = as a replacement for equality testing. Use == for equality comparisons.
Omitting parentheses in a complex condition The expression may be grouped differently than expected. Use parentheses to communicate the intended logic.
Using || when every condition must be true The expression succeeds when only one condition is true. Use && when all requirements must be satisfied.
Using && when either condition is sufficient The expression fails unless both conditions are true. Use || when either alternative is acceptable.
Assuming numeric values are Boolean Java does not treat 0 or 1 as false or true in conditions. Use a Boolean expression or an explicit comparison.

16. Practical Example: Student Eligibility Checker

This example uses logical operators to determine whether a student qualifies for an examination based on attendance and marks.

Source Code

public class StudentEligibility {
    public static void main(String[] args) {
        int attendance = 85;
        int marks = 65;
        boolean feesPaid = true;

        boolean eligible = attendance >= 75
                && marks >= 40
                && feesPaid;

        if (eligible) {
            System.out.println("Student is eligible for the examination.");
        } else {
            System.out.println("Student is not eligible for the examination.");
        }
    }
}

Output

Student is eligible for the examination.

Explanation

  • Attendance is at least 75, so the first condition is true.
  • Marks are at least 40, so the second condition is true.
  • Fees have been paid, so the third condition is true.
  • All conditions are true, so the student is eligible.

17. Practical Example: Discount Eligibility

A store may offer a discount when a customer is a premium member or the total purchase reaches a specified threshold.

Source Code

public class DiscountEligibility {
    public static void main(String[] args) {
        double purchaseAmount = 1500.00;
        boolean premiumMember = false;

        if (premiumMember || purchaseAmount >= 1000.00) {
            System.out.println("Discount applied.");
        } else {
            System.out.println("No discount available.");
        }
    }
}

Output

Discount applied.

The customer qualifies because the purchase amount meets the threshold, even though the customer is not a premium member.

18. Practical Mini Project: Basic Access Control

Build a simple program that evaluates whether a user can access a protected feature. The user must be logged in, the account must not be suspended, and the user must either be an administrator or have permission to view the feature.

Source Code

public class AccessControl {
    public static void main(String[] args) {
        boolean loggedIn = true;
        boolean suspended = false;
        boolean administrator = false;
        boolean hasViewPermission = true;

        boolean canAccess = loggedIn
                && !suspended
                && (administrator || hasViewPermission);

        if (canAccess) {
            System.out.println("Access granted.");
        } else {
            System.out.println("Access denied.");
        }
    }
}

Expected Output

Access granted.

Project Tasks

  • Change loggedIn to false and observe the result.
  • Set suspended to true and observe the result.
  • Set both administrator and hasViewPermission to false.
  • Add a Boolean variable for whether the requested feature is enabled.
  • Use parentheses to make the permission rules easy to understand.

This project demonstrates how multiple logical operators can express a clear access rule. Real applications should enforce permissions in the trusted application or server layer, not solely in a client-side check.

19. Practice Exercises

Exercise 1: Number Range

Write a program that checks whether an integer is between 1 and 100, inclusive, using the logical AND operator.

Exercise 2: Weekend Checker

Create an integer variable for a day number. Use the logical OR operator to check whether the value represents Saturday or Sunday.

Exercise 3: NOT Operator

Create a Boolean variable named isAvailable. Print its opposite value using the logical NOT operator.

Exercise 4: Login Conditions

Create Boolean variables for valid username, valid password, and locked account. Allow login only when the username and password are valid and the account is not locked.

Exercise 5: Short-Circuit Behavior

Create a method that prints a message and returns a Boolean value. Compare the behavior of && with & and || with |.

Exercise 6: De Morgan's Laws

Write two equivalent Boolean expressions using De Morgan's laws. Test both expressions with different combinations of true and false values.

Exercise 7: Discount Calculator

Allow a discount when the purchase is above a certain amount or when the customer is a premium member. Test at least four combinations of purchase amount and membership status.

20. Interview Questions and Answers

Q1. What are logical operators in Java?

Answer: Logical operators evaluate Boolean expressions. The main logical operators are AND (&&), OR (||), and NOT (!).

Q2. What is the difference between && and ||?

Answer: AND returns true only when both operands are true. OR returns true when at least one operand is true.

Q3. What is short-circuit evaluation?

Answer: Short-circuit evaluation stops evaluating an expression as soon as its result is determined. For example, false && expression skips the second operand, and true || expression also skips the second operand.

Q4. What is the difference between && and &?

Answer: For Boolean operands, both perform AND logic, but && short-circuits while & evaluates both operands. The single & operator can also perform bitwise AND on integral values.

Q5. What is the difference between || and |?

Answer: For Boolean operands, both perform OR logic, but || short-circuits while | evaluates both operands. The single | operator can also perform bitwise OR on integral values.

Q6. Can logical operators be used with integers directly?

Answer: Java logical operators require Boolean operands. To test an integer, use a comparison such as number > 0. Single & and | can operate on integral values as bitwise operators.

Q7. What does the NOT operator do?

Answer: The ! operator reverses a Boolean value. For example, !true evaluates to false.

Q8. Why is short-circuit evaluation useful?

Answer: It can avoid unnecessary work and safely skip expressions that should not run unless a preceding condition is satisfied, such as checking a reference for null before calling a method on it.

Q9. What are De Morgan's laws?

Answer: They state that !(A && B) is equivalent to !A || !B, and !(A || B) is equivalent to !A && !B.

Q10. How can parentheses improve logical expressions?

Answer: Parentheses explicitly show how parts of a complex expression should be grouped, improving readability and reducing mistakes caused by misunderstanding operator precedence.

Q11. What happens when the first operand of A && B is false?

Answer: Java skips evaluating B because the entire AND expression must be false.

Q12. What happens when the first operand of A || B is true?

Answer: Java skips evaluating B because the entire OR expression must be true.

21. Quick Revision Checklist

  • && means logical AND.
  • || means logical OR.
  • ! means logical NOT.
  • AND returns true only when both operands are true.
  • OR returns true when at least one operand is true.
  • NOT reverses the Boolean value.
  • && and || use short-circuit evaluation.
  • Boolean & and | evaluate both operands.
  • Single & and | can also perform bitwise operations on integral values.
  • Comparison operators can be combined with logical operators.
  • Use parentheses to clarify complex conditions.
  • De Morgan's laws help simplify negated Boolean expressions.
  • Logical operators are useful in conditions, loops, validation, and access rules.

22. Conclusion

Logical operators are essential in Java because they allow programs to evaluate multiple conditions and make decisions. The AND operator checks whether all required conditions are true, the OR operator checks whether at least one condition is true, and the NOT operator reverses a Boolean result.

Understanding short-circuit evaluation, operator precedence, and the difference between logical and bitwise operators helps you write safer and more readable code. Practise combining logical operators with comparisons, conditional statements, and loops to strengthen your Core Java fundamentals.

Continue your learning with the Core Java Training Course at JustAcademy, register for a course demo, or visit the JustAcademy website.

whatsapp