Logical operators in Java

Logical operators in Java

06 Sep 2024
Beginner
2.03K Views
14 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

Logical Operators in Java: An Overview

We already discussed the Types of Operators in the previous article. In this Java tutorial, we'll explore the syntax, types, and examples of logical operators in Java. Because Java is a flexible and widely used programming language, it has a powerful set of logical operators for manipulating Boolean values.

To further enhance your understanding and application of logical operator's concepts, consider enrolling in the best Java Full Stack Developer Course, to gain knowledge about effective utilization of logical operators for improved problem-solving and time management.

What are the Logical Operators in Java?

Logical operators in Java are special symbols or keywords that perform logical operations on Boolean values. These operators allow developers to combine or manipulate Boolean expressions, resulting in a single Boolean value. The three main logical operators in Java are:

  • The Logical AND operator produces true if both conditions under evaluation are true; otherwise, it returns false.
  • The Logical OR operator produces true if either of the supplied conditions is true. The OR operator returns false if and only if both conditions under evaluation are false.
  • The Logical NOT operator receives a single value as input and returns its inverse. In contrast to the Logical AND and, Logical OR operators, this is a unary operator.

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

Read More - Advanced Java Multithreading Interview Questions

Types of Logical Operators

Types of Logical Operators

1. && (Logical AND)

Only the "logical AND operator" returns true if both operands are 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)

Logical NOT is an Unary Operator, which means it only works with single operands. It reverses the value of operands; if the value is true, it returns false; if the value is false, it returns 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

Advantages of Logical Operators in Java

  • Logical operators increase code readability by simplifying difficult situations, resulting in greater comprehension among developers.
  • They increase flexibility by mixing operators in different ways, allowing for dynamic responses to program changes.
  • They promote code reuse, reducing redundancy and streamlining the development process.
  • Furthermore, logical operators make debugging easier, aiding in the detection of unusual behavior and speeding up issue resolution.

Disadvantages of Logical Operators in Java

  • Logical operators increase code readability by simplifying difficult situations, resulting in greater comprehension among developers.
  • They increase flexibility by mixing operators in different ways, allowing for dynamic responses to program changes.
  • They promote code reuse, reducing redundancy and streamlining the development process.
  • Furthermore, logical operators make debugging easier, aiding in the detection of unusual behavior and speeding up issue resolution.
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

This was all about the types of logical operators in Java. Logical operators in Java are essential tools for constructing complex conditions and decision-making structures in programs. Understanding the syntax and behavior of logical operators is crucial for writing efficient and error-free code. If you're interested in more tips and guidance, you may also consider our Java Full Stack Developer Training, 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.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

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.
Accept cookies & close this