Logical operators in Java

Logical operators in Java

28 Mar 2024
Beginner
538 Views
14 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

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 Certification 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

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 Online Course, which can validate your skills and enhance your credibility in the field.

FAQs

Q1. Can logical operators be used with non-boolean values in Java?

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

Q2. What is short-circuit evaluation in logical operators?

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.

Q3. How are logical operators different from bitwise operators in Java?

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
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this