Let's Learn Logical Operators in Java

Let's Learn Logical Operators in Java

5 mins readComment
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!

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

Free
6 months
โ€“ / โ€“
350 hours
Free
2 hours
Free
2 hours
Free
9 hours
โ€“ / โ€“
6 weeks
Free
55 hours
Free
25 hours
โ€“ / โ€“
โ€“ / โ€“
โ€“ / โ€“
4 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
Java String Compare: A Guide to Effective String Comparison in Java
Have you ever wondered how to compare strings in Java? You can use various methods for that, like using equals(), using == Operator, using equalsIgnoreCase(), using compareTo() and using compareToIgnoreCase()....read more

What are Identifiers in Java?
What are Identifiers in Java?
Have you ever wondered how Java keeps everything organized and accessible? It's all because of identifiers. Those unique labels assigned to variables, methods, and classes. These crucial elements of Java...read more

Getting Started with Java Hello World Program
Getting Started with Java Hello World Program
Do you know the significance of the "Hello World" program in Java? It's the first step for many into the world of programming, serving as a simple yet profound introduction...read more

All About Assignment Operator in Java
All About Assignment Operator in Java
Have you ever wondered how assignment operators function in Java? They are special symbols used for assigning values to variables, with the most basic one being the equal sign (=)....read more

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
Array Programs in Java | Beginner to Expert Level
Array programs in Java traverse from basic single-dimensional arrays to complex multi-dimensional arrays and dynamic arrays using ArrayList. From initializing and accessing array elements, to advanced operations like sorting and...read more

A Guide to Power Function in Java
A Guide to Power Function in Java
Have you ever wondered how mathematical power functions are implemented in programming languages like Java? In Java, the Math.pow() function is a powerful tool used to raise a number to...read more

Java Comments | About, Types and Examples
Java Comments | About, Types and Examples
Do you know what makes the code more readable? Comments, as they provide valuable context and explanations about the code, making it easier for both the original developers and others...read more

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