×

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These operators are of great importance in java as it helps to perform several crucial operations in java.

We will understand the types of logical operators with the aid of certain examples as well as some programs.

With the help of logical operators, one can execute logical “AND”, “OR” and “NOT” operations, just like “AND”, “OR” and “NOT” operations in digital electronics.

The gist of three logical operators.

  1. AND Operator ( && ) – if( a && b ) [if both the conditions are true, it executes otherwise it doesn’t]
  2. OR Operator ( || ) – if( a || b) [if one of the conditions is true, it executes otherwise it doesn’t]
  3. NOT Operator ( ! ) – !(a<b) [It returns false if the value of a is less than that of  b]

Now, let us try to understand each of the three operators in detail through examples and java code.

AND Operator

Syntax - if(a && b )

Here, a refers to condition 1 and b refers to condition 2.

Itreturns only if both the conditions are true, otherwise, it doesn’t.

Its symbol is &&.

Example

x = 12, y = 15, z = 22

To check if the variable z is the largest among the three.

If both of these conditions are satisfied, only then we can conclude that z is the largest.

if(z > x && z > y)

Condition 1: if (z > x) // (22 > 12) // TRUE

Condition 2: if (z > y) // (22 > 15) // TRUE

Therefore, z is the largest.

If both of these conditions are satisfied, only then we can conclude that z is the largest.

Truth Table:

aba && b
111
100
010
000
  • If condition 1 and condition 2 are true, the resultant is also true.
  • If condition 1 is true and condition 2 is false, the resultant is false.
  • If condition 1 is false and condition 2 is true, the resultant is false.
  • If condition 1 is false and condition 2 is false, the resultant is false.

Implementation

Now, we will see a java program to understand the concept even better.

Example 1:

// Java code to illustrate the working of
// logical AND operator


import java.io.*;


class Logical_operator {
    public static void main(String[] args)
    {
        // initializing the variables
        int a1 = 35, a2 = 45, a3 = 12, a4 = 0;


        // Displaying a, b, c
        System.out.println("Variable 1 = " + a1);
        System.out.println("Variable 2 = " + a2);
        System.out.println("Variable 3 = " + a3);


        // using the logical AND to verify


        if ((a1 < a2) && (a2 == a3)) {
            a4 = a1 + a2 + a3;
System.out.println(" sum = " + a4);
        }
        else
System.out.println(" conditions are False ");
    }
}

Output:

Types of Logical Operators in Java

Explanation: In this java code, an illustration of the logical AND operator is shown.

Example 2:

import java.io.*;


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


// initializing the variables
int a1 = 30, a2 = 40, a3 = 36;


// printing the value of variable b
System.out.println("Value of a2 : " + a2);


// Using logical AND operator
// Short-Circuiting effect as condition 1 is
// incorrect, thus condition 2 is never been touched
// and so ++a2 (pre-increment) doesn't take place and
// the value of a2 remains unchanged
if ((a1 > a3) && (++a2 > a3)) {
System.out.println("Inside the if block");
}


// Printing the value of a2
System.out.println("Value of a2 : " + a2);
}
}

Output:

Types of Logical Operators in Java

Explanation: In this java code, an illustration of the logical AND operator is shown. Here, the case of the short circuit effect is illustrated.

OR Operator 

Syntax – if(a || b)

Here, a refers to condition 1 and b refers to condition 2.

Itreturns even if the only condition is true. If the first operand is true, it doesn’t even check the second operand.

Its symbol is ||.

Example

x = 5, y = 8

z = (x > 0 || y > 0) // (5 > 0 || 8 > 0)

5 > 0 // TRUE

The first condition is true, so the resultant is true and there is no need to check the second condition.

Truth Table:

aba && b
111
101
011
000

If condition 1 and condition 2 are true, the resultant is also true.

If condition 1 is true and condition 2 is false, the resultant is true as the working of the OR operator is such that even if one of the conditions is true, the output is also true.

If condition 1 is false and condition 2 is true, the resultant is true.

If condition 1 is false and condition 2 is false, the resultant is false.

Implementation:

Now, we will see a java program to understand the concept even better.

// Java code to understand the working
// logical OR operator


import java.io.*;


class Logical_operator {
public static void main(String[] args)
{
// initializing variables
    int a1 = 35, a2 = 45, a3 = 12, a4 = 0;


// printng the values of a1, a2, a3
System.out.println("Variable 1 = " + a1);
System.out.println("Variable 2 = " + a2);
System.out.println("Variable 3 = " + a3);
System.out.println("Variable 4 = " + a4);


// logical OR operators being used

if (a1 > a2 || a3 == a4)
System.out.println("Either of the two conditions are true");
else
System.out.println("Neither of the two conditions are true");
}
}

Output:

Types of Logical Operators in Java

Explanation: In this java code, an illustration of the logical OR operator is shown.

NOT Operator 

Syntax -!(condition)

If the value is true, it will return false, and vice versa.

Its symbol is !.

Example

y = !(0)

output – 1

y = !(x == 5)

output - 0

a = 5, b = 7

!(a<b) // !(5 < 7) // !(true) // false

It complements the result. It gives out false if the result was true and true if the result was false.

Truth Table:

ab
01
10

Implementation:

Now, we will see a java program to understand the concept even better.

// Java code to understand the working of
// logical NOT  in java


import java.io.*;


class Logical {
public static void main(String[] args)
{
// initializing the variables
int a1 = 22, a2 = 1;


// Printing the values of a1 and a2
System.out.println("Variable 1 = " + a1);
System.out.println("Variable 2 = " + a2);


//  logical NOT operator being used
System.out.println("!(a1 < a2) = " + !(a1 < a2));
System.out.println("!(a1 > a2) = " + !(a1 > a2));
}
}

Output:

Types of Logical Operators in Java

Explanation: In this java code, an illustration of the logical NOT operator is shown.

Example of Logical Operator

Illustrating the working of logical AND, logical OR, and logical NOT operators together in one java program.

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


    int a = 4, b = 6;
    // illustrate the working of && operator
System.out.println("Outputs of AND operator"); 
boolean x = ((a > b) && (a > b));
System.out.println(x);  
    x = ((a > b) && (a < b));
System.out.println(x);  


    // illustrate the working of || operator
System.out.println("Outputs of OR operator"); 
    x = (a < b) || (a > b);
System.out.println(x);
    x = (a > b) || (a < b);
System.out.println(x);  
    x = (a < b) || (a < b);
System.out.println(x);  
    x = (a > b) || (a > b);
System.out.println(x);


    // illustrate the working of! operator
System.out.println("Outputs of NOT operator"); 
    x = !(a == b);
System.out.println(x);  
    x = !(a > b);
System.out.println(x);  
  }
}

Output:

Types of Logical Operators in Java

Explanation: In this java code, an illustration of the logical AND, logical OR, and logical NOToperatorsare shown.

Summary

This tutorial was all about the types of logical operators in Java language. We saw the three logical operators namely – logical AND, logical OR, and logical NOT. We saw the syntax, truth table, and working of each of these operators and finally, undertook a practical approach for which we wrote java codes to understand the concept even better.


Related Topics

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.