top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Logical Operators in Java

Introduction 

Programming languages employ symbols called operators to carry out certain mathematical, relational, or logical operations. Programming languages use logical operators to analyze Boolean data type values and create Boolean expressions that regulate program flow. The three logical operators in Java are AND (&&), OR (||), and NOT (!).

Overview

The conditional or, symbolized by ||, and the conditional and, denoted by &&, are examples of logical operators. The results or outputs of logical processes are true or false Boolean values. 

Here's a table with the Java logical operators:

Operator

Description

&&

Conditional AND

||

Conditional OR

!

Logical NOT

This tutorial will examine these logical operators in Java with examples, their usage, and their behavior in various contexts.

Features of Logical Operators In Java (With Example)

AND Operator (&&)

The && operator is a binary operator that performs the logical AND operation between two boolean expressions. It returns true only if both operands are true. Otherwise, it returns false. It employs short-circuit evaluation, meaning that if the left operand evaluates to false, the right operand is not evaluated.

Example:

boolean a = true;
boolean b = false;
boolean result = A && B;

OR Operator (||)

The || operator is a binary operator that performs the logical OR operation between two boolean expressions. It returns true if either or both operands are true. It returns false only if both operands are false. Similar to the AND operator, it also employs short-circuit evaluation.

Example:

boolean a = true;
boolean b = false;
boolean result = A || B;

NOT Operator (!)

The ! operator is a unary operator that performs the logical NOT operation on a boolean expression. It returns the opposite of the boolean value of the operand. If the operand is true, the NOT operator returns false, and vice versa.

Example:

boolean a = true;
boolean result = !A;

XOR Operator (^)

The ^ (exclusive OR) operator is a binary operator that performs the logical XOR operation between two boolean expressions. It returns true if the operands have different boolean values (true and false or false and true). It returns false if the operands have the same boolean value. Unlike the AND and OR operators, the XOR operator does not employ short-circuit evaluation.

Example:

boolean a = true;
boolean b = false;
boolean result = A ^ B;

Logical Operators Table

Applying the logical operators in the Java truth tables show the output of the AND and OR operators:
A
B
A && B
T
T
T
T
F
F
F
T
F
F
F
F
A
B
A || B
T
T
T
T
F
T
F
T
T
F
F
F
The NOT operator is a unary operator and only takes one operand. It returns the opposite of the given boolean value:
A
!A
T
F
F
T

Java Logical Operators with Examples

Logical ‘AND’ Operator (&&)

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


        boolean result = a && b;


        System.out.println("Result: " + result); // Output: Result: false
    }
}

In the above program, the boolean variables a and b are declared and assigned values. The && operator is then used to perform the logical AND operation between a and b. The result of the operation is stored in the boolean variable result.

Finally, the result is printed using System.out.println(), which displays "Result: false" because the logical AND operator returns true only if both operands are true. In this case, a is false, and b is true, so the result is false.

Logical ‘OR’ Operator (||)

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


        boolean result = a || b;


        System.out.println("Result: " + result); // Output: Result: true
    }
}

In this program, the boolean variables a and b are declared and assigned values while the || operator is used to perform the logical OR operation between a and b. Like the previous program, the result of the operation is stored in the boolean variable result and is printed using System.out.println().

The output displays "Result: true" because the logical OR operator returns true if either or both operands are true. In this case, a is false, and b is true, so the result is true.

Logical ‘NOT’ Operator (!)

public class upGradTutorials {
    public static void main(String[] args) {
        boolean a = true;

        boolean result = !a;

        System.out.println("Result: " + result); // Output: Result: false
    }
}

In the above example, only the boolean variable a is declared and assigned the value true. The ! operator is then used to perform the logical NOT operation on a. As usual, we store the result of the operation in the boolean variable result.

Finally, the result is printed using System.out.println(), which displays "Result: false" because the logical NOT operator returns the opposite boolean value of the operand. Since a is true, the result is false.

Logical ‘XOR’ Operator (^)

public class upGradTutorials {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = true;


        boolean result = a ^ b;


        System.out.println("Result: " + result); // Output: Result: false
    }
}

In this example, the boolean variables a and b are declared and assigned the value true.

We use the ^ operator to perform the logical XOR (exclusive OR) operation between a and b. The result of the operation is stored in the boolean variable result and then printed using System.out.println(), which displays "Result: false" because the logical XOR operator returns true if the operands have different boolean values (true and false, or false and true). 

In this case, both a and b are true, so the result is false.

Implementing all Logical operators on Boolean Values

Here is an example program that demonstrates the usage of all logical operators on boolean values (true or false) in Java:

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

        // Logical AND Operator (&&)
        boolean resultAnd = a && b;
        System.out.println("Logical AND Result: " + resultAnd);

        // Logical OR Operator (||)
        boolean resultOr = a || b;
        System.out.println("Logical OR Result: " + resultOr);

        // Logical NOT Operator (!)
        boolean resultNotA = !a;
        System.out.println("Logical NOT Result (A): " + resultNotA);
        boolean resultNotB = !b;
        System.out.println("Logical NOT Result (B): " + resultNotB);

        // Logical XOR Operator (^)
        boolean resultXor = a ^ b;
        System.out.println("Logical XOR Result: " + resultXor);
    }
}

The above program begins similarly by defining a class named upGradTutorials as we have been using. Inside the main method, two boolean variables, a and b, are declared and assigned values like in the individual logical operations. In this example, a is initialized with true, and b is initialized with false.

Now, we will work on the 4 different logical operations.

First, the && operator performs the logical AND operation between a and b. The result of the operation is stored in the resultAnd variable. The program then prints the result using System.out.println() and an appropriate message.

Second, the || operator performs the logical OR operation between a and b. The result of the operation is stored in the resultOr variable. The program prints the result using System.out.println().

Then, ! operator performs the logical NOT operation on a and b separately.

The operation result for a is stored in the resultNotA variable, and for b in the resultNotB variable. The program then similarly prints the results using System.out.println().

Finally, the ^ operator performs the logical XOR (exclusive OR) operation between a and b.

The result of the operation is stored in the resultXor variable. The program then prints this result using System.out.println() as well, making the program ends as the execution of the main method is complete.

Advantages of Logical Operators

Logical operators in Java have several advantages:

  • Flexibility: Logical operators can be coupled in several ways to generate complicated situations to the code's adaptability. This enables programmers to design code that can handle a wide range of circumstances and respond to changes in input flexibly.

  • Efficiency: Logical operators can improve program efficiency by minimizing the number of conditional statements that must be evaluated. To combine two criteria into a single statement that can be processed quicker than two separate ones, use the && operator.

  • Readability: Using logical operators to simplify the portrayal of challenging situations in code improves readability. They are easily recognizable and assist others in decoding the code.

  • Debugging: Logical operators can help engineers debug software by allowing them to detect specific scenarios causing difficulties.

  • Short-circuiting: In Java, logical operators utilize short-circuiting, which confines the evaluation of the second operand to the situation where the first operand is insufficient to determine the expression's conclusion. Program performance can be improved by avoiding superfluous assessments.

Disadvantages of Logical Operators

Here are some disadvantages of logical operators in Java:

  • Limited expressiveness: Logical operators have a limited expressive capacity compared to more complicated logical constructions like if-else statements.

  • Short-circuit evaluation: The short-circuit evaluation property of logical operators can occasionally lead to unexpected behavior.

  • Code readability: Overuse of logical operators can make code difficult to read and understand. Complex expressions with several logical operators might be difficult to understand and comprehend.

  • Code maintainability: Code that depends extensively on logical operators might be challenging to maintain and adapt. Changes to one section of a detailed statement might have unanticipated repercussions elsewhere in the code.

  • Limited applicability: Logical operators are only effective for simple decision-making contexts. More complicated decision-making typically demands more advanced structures like if-else expressions or switch statements.

Conclusion

Java provides logical operators for combining numerous conditional statements to obtain a boolean result. Logical operators in Java are useful tools for programmers since they aid in the execution of complex conditions. This allows programmers to create code that can deal with various situations and dynamically alter them in response to input changes. 

FAQs

1. What are bitwise logical operators in Java?

A bitwise logical operator in Java executes operations on individual bits of numeric data. Java has six bitwise operators: bitwise AND, bitwise OR, bitwise exclusive OR, bitwise complement, left shift, and right shift. These operators manipulate the low-level data directly and can be used with several integer types such as char, int, long, short, and byte.

2. How do Boolean logical operators in Java work with multiple values?

Combining one or more Boolean values in Java can generate a new Boolean value, depending on the Boolean logical operator employed. This is how it works.

3. What are assignment operators in Java?

In Java, assignment operators are used to assign values to variables. The equals sign (=) is the basic fundamental assignment operator, assigning the value on the right to the variable on the left. Compound assignment operators in Java include +=, -=, *=, and /=, which combine arithmetic operators with the simple assignment operator.

Leave a Reply

Your email address will not be published. Required fields are marked *