Logical Operators in Java Explained [Practical Examples]


JAVA

Introduction to Logical Operators in Java

In Java, Logical operators return a boolean value by evaluating two or more conditions. In other words, if we want multiple conditions to be evaluated before executing a set of steps, we can make use of the logical operators. This can be an alternative to writing nested if statements in some cases. Logical AND and Logical OR are binary operators whereas Logical NOT is a unary operator.

Java supports the following Logical operators.

  • Logical OR Operator(||)
  • Logical AND Operator(&&)
  • Logical NOT Operator (!)

 

Different types of Logical Operators in Java

Logical OR Operator (||)

In Java, the Logical OR operator "||" is a binary operator that operates on conditional statements on either side. This operator returns true if at least one of the conditions is true. Here, the logical || operator will not check the second condition if the first condition is true. However, It checks the second condition only if the first one is false.

The statement below demonstrates syntax of the "||" operator.

result = first_condition || second_condition

 

Example : In this example, we will get marks of maths, science and english from the student. Thereafter, we will check if the student qualifies for next level. To qualify for the next level, the student should have at least 60 marks in one subject.

import java.util.Scanner;
public class LogicalDemo
{
  public static void main(String[] args) 
	{
        // Creating Scanner object to get input from user
        Scanner sc = new Scanner(System.in);
		 
        // Get input from user
        System.out.println("Enter Maths Marks");
        int maths=sc.nextInt();
        System.out.println("Enter Science Marks");
        int science=sc.nextInt();
        System.out.println("Enter English Marks");
        int english=sc.nextInt();
		
        // Using logical OR operator
        if(maths>60 || science>60 || english>60)
            System.out.println("Congratulations... You are eligible for the next level");
        else
            System.out.println("Work hard.. You are not eligible for the next level");
       
    }
}

Output

Enter Maths Marks
55
Enter Science Marks
62
Enter English Marks
49
Congratulations... You are eligible for the next level

 

Logical AND Operator (&&)

In Java, the Logical AND operator "&&" is a binary operator that operates on conditional statements on either side. This operator returns true if both the conditions are true. In other words, logical && operator will not check the second condition if the first condition is false. However, It checks the second condition only if the first one is true.

The statement below demonstrates the syntax of "&&" operator.

result = first_condition && second_condition

Example : In this example, We will get a number from the user and check if that number lies in the range of 50 to 100.

// Importing Scanner
import java.util.Scanner;
public class LogicalDemo
{
  public static void main(String[] args) 
	{
       // Creating Scanner object to get input from user
          Scanner sc = new Scanner(System.in);
       // Get input from user
        System.out.println("Enter a number");
        int a=sc.nextInt();
        // Using logical AND operator
        if(a>50 && a<100)
            System.out.println("Valid Input");
        else
            System.out.println("Invalid Input");
       
    }
}

Output

Enter a number
45
Invalid Input

 

Logical NOT Operator (!)

In Java, the Logical NOT operator "!" is a unary operator that is used to reverses the logical state of its condition. In other words, if a result of the condition is true then Logical NOT operator will make it as false. Similarly, if the condition is false, it will make it true.

The statement below demonstrates the syntax of "!" operator.

result = ! condition

Example :

public class LogicalDemo
{
  public static void main(String[] args) 
	{
        // Initializing
        int a=10;
	
        // Using logical NOT Operator
        if(!(a<50))
            System.out.println("Value of a is greater than 50");
        else
            System.out.println("Value of a is less than 50");
       
    }
}

Output

Value of a is less than 50

 

Example using Logical AND, Logical OR and Logical NOT operators :

Example 1: This example demonstrates the use of all logical operators. Get a year from the user and check if it is a leap year or not.

import java.util.Scanner;
public class LogicalDemo
{
  public static void main(String[] args) 
	{
        // Creating scanner object and Declaring a variable
        Scanner sc=new Scanner(System.in);
        int y;
    
	// Input a year to check 
	System.out.println("Enter year: ");
	y=sc.nextInt();
    
	// Using logical AND, OR and NOT Operator
	if(!((y%400==0) || (y%4==0 && y%100!=0)))
		System.out.println(y+" is a not a leap year");
	else
		System.out.println(y+" is a leap year");
       
    }
}

Output

Enter year
2022
2022 is not a leap year

 

Example 2: This example demonstrates the use of all logical operators. Here, we will get the marks of maths, physics, chemistry, and computer from the student. To be eligible for admission, student must have obtained marks greater than 70 in computer whereas the average of other three subjects out of four subjects must be more than 60.

import java.util.Scanner;
public class LogicalDemo
{
  public static void main(String[] args) 
    {
        // Declaring variables
        String name;
        int maths, phy, chem, comp;
        // Declaring scanner object
        Scanner sc=new Scanner(System.in);
	
        // Scanning input from the user
	System.out.println("Enter Your Name");
	name=sc.nextLine();
	System.out.println("Enter your Maths marks");
	maths=sc.nextInt();
	System.out.println("Enter your Physics marks");
	phy=sc.nextInt();
        System.out.println("Enter your Chemistry marks");
	chem=sc.nextInt();
	System.out.println("Enter your Computer marks");
	comp=sc.nextInt();

        // Checking eligibility for admission 
	if(comp > 70 && ((maths+phy+chem)/3 > 60 || (maths+phy+comp)/3 >60))
	    System.out.println("You are eligible for an Engineering admission");  
       
    }
}

Output

Enter Your Name
Raj
Enter your Maths marks
45
Enter your Physics marks
60
Enter your Chemistry marks
50
Enter your Computer marks
75
You are eligible for an Engineering admission

 

Example 3: This example demonstrates the use of all logical operators. Here, we will get a name, age, salary from the user and check if a person is eligible for the relief package or not.

import java.util.Scanner;
public class LogicalDemo
{
  public static void main(String[] args) 
    {
        // Declaring a variables
        String name;
        int age, salary;
        // Declaring scanner object
        Scanner sc=new Scanner(System.in);
	
        // Scanning input from the user
	System.out.println("Enter Your Name");
	name=sc.nextLine();
	System.out.println("Enter your age");
	age=sc.nextInt();
	System.out.println("Enter your annual salary");
	salary=sc.nextInt();
        
        // Checking eligibility for relief package
	if((age > 60 && salary 55 && salary < 250000) )
	    System.out.println("You are eligible for relief package");  
       
    }
}

Output

Enter Your Name
Raj
Enter your age
57
Enter your annual salary
245000
You are eligible for relief package

 

Summary

The knowledge of Logical operators is a key to start building the logic in Java. The Logical operators are extensively used in programs with many constraints. This is a very good alternative to avoid the nested if statements and keep the code readable. In this tutorial, we covered all Logical operators supported in Java. We learned in detail about the syntax and how we can use this operators with example. All in all, this tutorial, covers everything that you need to know in order to have a solid command over Logical operators in Java.

 

References

Operators
More about Java Operators

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment