Let's Learn Logical Operators in Java

Let's Learn Logical Operators in Java

5 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Sep 3, 2024 13:50 IST

Have you ever wondered how logical operators in Java work? These operators, including AND (&&), OR (||), and NOT (!), are used to combine or invert boolean expressions, playing a critical role in controlling program flow and decision-making processes. Let's understand more!

Operators in Java are special symbols or keywords that are used to perform operations on variables and values. These operations can range from basic mathematical calculations to complex logical comparisons. Operators in Java are categorized into several types based on their functionality. In this blog, we will learn about one of its types in detail, which is the logical operators!

Table of Content

 
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
β‚Ή15 K
3 months
β‚Ή2.05 K
3 months
– / –
170 hours
β‚Ή5.4 K
1 month
– / –
2 months
– / –
6 months
β‚Ή5.5 K
1 month
β‚Ή17 K
3 months

What is a Logical Operator in Java?

Logical operators in Java are used to perform logical operations on boolean expressions. These operators are typically used in decision-making processes within the code, especially in conditional statements like if, while, and for. In real-world scenarios, the logic required for certain operations can be quite complex and may involve multiple variables and conditions. Logical operators enable the implementation of such complex logical sequences in an efficient and manageable way.

Types and Syntax of Logical Operator with Example

1. AND Operator (&&)

  • Syntax: booleanExpression1 && booleanExpression2
  • Usage: Returns true only if both booleanExpression1 and booleanExpression2 are true.

Example


 
public class AndOperatorExample {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
// Check if age is over 18 and has a driving license
if (age > 18 && hasLicense) {
System.out.println("Eligible to drive.");
} else {
System.out.println("Not eligible to drive.");
}
}
}
Copy code

Output

Eligible to drive.

2. OR Operator (||)

  • Syntax: booleanExpression1 || booleanExpression2
  • Usage: Returns true if either booleanExpression1 or booleanExpression2 is true.

Example


 
public class OrOperatorExample {
public static void main(String[] args) {
boolean isWeekend = true;
boolean isHoliday = false;
// Check if it is either a weekend or a holiday
if (isWeekend || isHoliday) {
System.out.println("Time to relax!");
} else {
System.out.println("Regular workday.");
}
}
}
Copy code

Output

Time to relax!

3. NOT Operator (!)

  • Syntax: !booleanExpression
  • Usage: Returns true if booleanExpression is false, and false if it is true.

Example


 
public class NotOperatorExample {
public static void main(String[] args) {
boolean isRaining = false;
// Check if it is not raining
if (!isRaining) {
System.out.println("Let's go for a walk!");
} else {
System.out.println("Stay indoors, it's raining.");
}
}
}
Copy code

Output

Let's go for a walk!

Java String Compare: A Guide to Effective String Comparison in Java

What are Identifiers in Java?

Getting Started with Java Hello World Program

All About Assignment Operator in Java

Examples Showing Usage of Logical Operator

Example 1: Checking Eligibility for a Contest

Problem Statement: Determine if a participant is eligible for a contest. The eligibility criteria are age between 18 and 30 and having a registration ID.


 
public class EligibilityCheck {
public static void main(String[] args) {
int age = 25;
boolean hasRegistrationId = true;
// Check if age is between 18 and 30 and has a registration ID
if (age >= 18 && age <= 30 && hasRegistrationId) {
System.out.println("Eligible for the contest.");
} else {
System.out.println("Not eligible for the contest.");
}
}
}
Copy code

Output

Eligible for the contest.

Here, the && operator is used to ensure all conditions (age between 18 and 30 and having a registration ID) are met. Since both conditions are true, the output is "Eligible for the contest."

Example 2: Planning an Activity Based on Weather

Problem Statement: Decide whether to go hiking, depending on the weather. Go hiking only if it is not raining and not too hot (temperature below 30 degrees Celsius).


 
public class ActivityPlanner {
public static void main(String[] args) {
boolean isRaining = false;
int temperature = 25; // in degrees Celsius
// Check if it's not raining and temperature is below 30 degrees Celsius
if (!isRaining && temperature < 30) {
System.out.println("Perfect day for hiking!");
} else {
System.out.println("Let's find another activity.");
}
}
}
Copy code

Output

Perfect day for hiking!

The code uses !isRaining (NOT operator) to check it's not raining and temperature < 30 (AND operator) to ensure a favourable temperature. Both conditions are true, so the output is "Perfect day for hiking!"

Example 3: Movie Night Decision

Problem Statement: Decide to have a movie night if it's either a weekend or a holiday.


 
public class MovieNight {
public static void main(String[] args) {
boolean isWeekend = false;
boolean isHoliday = true;
// Check if it's either a weekend or a holiday
if (isWeekend || isHoliday) {
System.out.println("Let's have a movie night!");
} else {
System.out.println("Maybe another day.");
}
}
}
Copy code

Output

Let's have a movie night!

The || operator is used to check if either it's a weekend or a holiday. Since it's a holiday, the condition evaluates to true, leading to the output "Let's have a movie night!"

Array Programs in Java | Beginner to Expert Level

A Guide to Power Function in Java

Java Comments | About, Types and Examples

Conclusion

Relational operators in Java are essential tools for comparing two values or expressions and returning a boolean result based on that comparison. These operators are fundamental in control flow statements such as if, while, and for loops, where decisions are made based on the relationship between values. 

FAQs

What are Logical Operators in Java?

Logical operators in Java are used to perform logical operations on boolean expressions. The main logical operators are && (logical AND), || (logical OR), and ! (logical NOT). They are used to evaluate conditions and return a boolean result (true or false).

How Does the && (AND) Operator Work?

The && operator returns true if and only if both operands are true. For example, if (a > b && b > c) evaluates to true only if both a > b and b > c are true. If either of the conditions is false, the whole expression evaluates to false.

What is the Function of the || (OR) Operator?

The || operator returns true if at least one of the operands is true. For instance, in if (a > b || b > c), the entire expression is true if either a > b or b > c is true (or both).

How is the ! (NOT) Operator Used?

The ! operator inverts the value of a boolean expression. It turns true into false and vice versa. For example, if (!a) is true if a is false.

What is the Difference Between & and &&, | and ||?

& and | are bitwise operators and also work as logical operators, but they don't support short-circuiting. && and || are logical operators that do support short-circuiting. For example, in a && b, if a is false, b is not evaluated because the result will be false regardless. In contrast, with a & b, both a and b are evaluated irrespective of the value of a.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio