Logical operators in Java

Logical operators in Java

05 Jul 2025
Beginner
3.1K Views
20 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

Logical operators are special symbols or words used in programming to connect two or more conditions or expressions. They help evaluate whether the combined condition is true or false, allowing the program to make decisions and execute specific actions based on the result.

To further enhance your understanding and application of logical operators' concepts, consider enrolling in the best Java Online Course Free With Certificate to gain knowledge about ethe ffective utilization of logical operators for improved problem-solving and time management.

What are the Logical Operators in Java?

Logical Operators in Java

Logical operators in Java are special symbols used to perform operations on Boolean values or expressions. They enable developers to combine multiple conditions or manipulate Boolean logic, resulting in a single true or false outcome. These operators are commonly used in control flow statements such as if, while, and for. Java provides three primary logical operators:

  • AND (&&) – Returns true only if both conditions are true.
  • OR (||) – Returns true if at least one of the conditions is true.
  • NOT (!) – Reverses the boolean value of the condition.

Syntax:

result = operand1 logical_operator operand2;

Here, operand1 and operand2 are numeric values or variables, and logical_operator is the logical operator that defines the operation to be performed.

Read More - Java 50 Interview Questions,|Advanced Java Multithreading Interview Questions

Types of Logical Operators

Types of Logical Operators

1. && (Logical AND)

The logical AND operator (&&) checks two boolean expressions and returns true only if both expressions evaluate to true. If either one or both are false, the result is false.
Only the "logical AND operator" returns true.
Syntax
result = operand1 && operand2;

Example

import java.util.Scanner;

class LogicalOperator {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter value of x: ");
    int x = sc.nextInt();

    System.out.print("Enter value of y: ");
    int y = sc.nextInt();

    System.out.print("Enter value of z: ");
    int z = sc.nextInt();

    if ((x < y) && (x < z)) {
      System.out.println("Minimum: " + x);
    } 
    else if ((y < x) && (y < z)) {
      System.out.println("Minimum: " + y);
    } 
    else {
      System.out.println("Minimum: " + z);
    }

    sc.close();
  }
}

Explanation

The approach described above in the Java Online Editor finds the minimum number from X, Y, and Z (which are inputs). If X is the minimum of the X, Y, and Z variables, then the conditions X > Y and Y > Z should be satisfied. As a result, we used the AND (&&) operator to combine these two requirements. For Y, the same logic is used. If X and Y are not the minimum, the minimum must be Z.

Output

Enter value of x: 10
Enter value of y: 50
Enter value of z: 40
Minimum: 10

2. || (Logical OR)

When one of its operands returns true, the logical OR operator is evaluated as true. The result is true if either or both expressions convert to true.

Syntax

boolean result = operand1 || operand2;

Example

import java.util.Scanner;
class LogicalOperator {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter value of x: ");
    int x = sc.nextInt();

    System.out.print("Enter value of y: ");
    int y = sc.nextInt();

    System.out.print("Enter value of z: ");
    int z = sc.nextInt();

    // || operator
    System.out.println((x < y) || (z > x));  
    System.out.println((x > y) || (z < x));  
    System.out.println((x < y) || (z < x));  

    sc.close();
  }
} 

Explanation

In this example, the user gives input values for three variables (x, y, and z), and it evaluates and prints the results of three different logical OR operations using the input values and the specified conditions. The logical OR operator returns true if at least one of the conditions is true.

Output

Enter value of x: 10
Enter value of y: 20
Enter value of z: 30
true
false
true

3. ! (Logical NOT)

The logical NOT operator (!) is a unary operator that reverses the value of a boolean expression. If the expression is true, it becomes false, and if it is false, it becomes true.

Syntax

boolean result = !operand;

Example

import java.util.Scanner;
class LogicalOperator {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter value of x: ");
    int x = sc.nextInt();

    System.out.print("Enter value of y: ");
    int y = sc.nextInt();

    System.out.println(!(x == y));  
    System.out.println(!(x > y));  

    sc.close();
  }
}

Explanation

In this example, the user takes two integer inputs from the user, performs logical NOT operations on equality and greater-than conditions, and prints the results to the console. The logical NOT operator (!) inverts the Boolean values of the conditions, providing an output that represents the negation of the original expressions.

Output

Enter value of x: 26
Enter value of y: 12
true
false   

Read More - Java Certification Salary

Examples of Logical Operators in Java


  class LogicalOperator {
  public static void main(String[] args) {

      // && operator
      System.out.println((4 > 3) && (7 > 6)); // true
      System.out.println((4 > 3) && (7 < 6)); // false

      // || operator
      System.out.println((4 < 3) || (7 > 6)); // true
      System.out.println((4 > 3) || (7 < 6)); // true
      System.out.println((4 < 3) || (7 < 6)); // false

      // ! operator
      System.out.println(!(4 == 3)); // true
      System.out.println(!(4 > 3)); // false
  }
}
        

Explanation

The above code in the Java Playground illustrates how logical operators combine and manipulate Boolean values to produce different results based on the specified conditions. It is a practical example that showcases the behavior of logical operators in Java.

Output

true
false
true
true
false
true
false      

Logical Operators Table

Operand 1Operand 2&& (Logical AND)|| (Logical OR)! (Logical NOT)
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruefalse
falsefalsefalsefalsetrue

Common Mistakes to Avoid with Logical Operators in Java

1. Mixing Up && and &, or || and |

  • && and || are logical operators (used with boolean conditions).
  • & and | are bitwise operators (used with binary numbers).
  • Mistaking one for the other can lead to unexpected results or performance issues.

2. Forgetting Short-Circuit Behavior

  • Logical && and || use short-circuiting, meaning they stop checking as soon as the result is clear.
  • This is helpful, but if the second condition has side effects (like a method call), it may not run as expected.

3. Writing Overly Complex Conditions

  • Combining too many conditions in one line can make the logic hard to read and debug.
  • Break them into smaller parts if possible for clarity.

4. Misunderstanding! (NOT Operator)

  • Beginners often misuse !, especially when checking for false values.
  • For example, writing if (!isActive == true) instead of simply if (!isActive).

5. Assuming All Conditions Will Be Checked

  • With short-circuit operators, the second condition won’t run if the result is already known.
  • This can cause problems if the skipped condition includes important operations.

6. Using Logical Operators with Non-Boolean Values

  • Logical operators should only be used with true or false.
  • Using them with non-boolean types (like numbers or strings) will cause compilation errors.

7. Not Grouping Conditions Properly with Parentheses

  • If you don’t use parentheses, Java might not evaluate the conditions in the order you expect.
  • Use () to control the order of evaluation clearly.

Advantages of Logical Operators in Java

1. Join Two or More Conditions

  • You can check many conditions at once using logical operators, instead of writing separate checks.

2. Make Code Short and Clear

  • They help you write less code that is easier to read and understand.

3. Save Time During Execution

  • Java stops checking conditions when it already knows the answer, which saves time.

4. Avoid Repeating Code

  • You don’t need to write long or repeated statements—just use logical operators to simplify things.

5. Used in If Statements and Loops

  • They are very useful in decision-making parts of the code, like if, while, and for.

6. Skip Unnecessary Checks

  • If the result is already clear, Java skips checking the rest—this prevents extra work and errors.

7. Useful in Real-Life Programs

  • They are used in login systems, form checks, filters, and other everyday features.

8. Make Programs Work Better

  • Logical operators help your code run smoothly and do the right thing at the right time.

Disadvantages of Logical Operators in Java

1. Can Make Code Confusing

  • If too many conditions are combined, it can be hard to read and understand the logic.

2. Difficult to Debug

  • When something goes wrong in a complex condition, it can be tricky to find out what part is causing the issue.

3. Overuse Can Reduce Clarity

  • Using many logical operators in one line may make the code look messy and complicated.

4. Short-Circuiting May Cause Mistakes

  • Java stops checking further conditions if the result is already known, which might skip important parts if not used carefully.

5. Not Suitable for All Situations

  • In some cases, writing separate if statements is better for clarity and easier debugging.

6. Requires Understanding of Boolean Logic

  • Beginners might find it hard to understand how true and false work when many conditions are joined together.

Explore More Operators in Java

  1. Relational operators in Java
  2. Arithmetic operators in Java
  3. Assignment operator in Java
  4. Unary operator in Java
  5. Bitwise operator in Java
  6. Ternary operator in Java
Summary

To further deepen your understanding and practical use of logical operators in Java, consider enrolling in a top-rated free Java online course with a certificate. These courses offer comprehensive lessons and real-world coding practice, helping you apply logical operator concepts effectively. This knowledge can greatly enhance your problem-solving skills, improve coding efficiency, and support better time management during programming tasks and technical interviews. Investing in such learning resources is a smart move toward becoming a skilled and confident Java developer.

If you're interested in more tips and guidance, you may also consider our Java Free Certification Course, which can validate your skills and enhance your credibility in the field.

FAQs

No, logical operators are specifically designed to operate on boolean values. Using them with non-boolean types will result in a compilation error.

Short-circuit evaluation is a feature where the second operand is not evaluated if the result can be determined by evaluating the first operand. This helps improve performance in certain situations.

While logical operators operate on Boolean values and produce Boolean results, bitwise operators work at the bit level and are used for integer types. Logical operators are used for decision-making and control flow, while bitwise operators in java are used for low-level bit manipulation.

Take our Java skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Live Training - Book Free Demo
.NET Solution Architect Certification Training
12 Jul
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
React Certification Training
12 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
.NET Microservices Certification Training
12 Jul
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Azure Developer Certification Training
14 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Azure AI & Gen AI Engineer Certification Training Program
17 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this