Java Logical Operators


Logical operators in Java are used to combine one or more boolean expressions to produce a single boolean value. They are primarily used in conditional statements to evaluate multiple conditions simultaneously. Here’s a detailed explanation of logical operators along with examples.

List of Logical Operators in Java

OperatorDescriptionExample
&&Logical ANDa && b
``
!Logical NOT!a

1. Logical AND Operator (&&)

The logical AND operator returns true if both operands (conditions) are true; otherwise, it returns false.

Example:

public class LogicalAndExample { public static void main(String[] args) { boolean condition1 = true; boolean condition2 = false; // Using the logical AND operator boolean result = condition1 && condition2; // Evaluates to false System.out.println("Condition1 AND Condition2: " + result); // Output: Condition1 AND Condition2: false // Example in a conditional statement int age = 25; boolean hasLicense = true; if (age >= 18 && hasLicense) { System.out.println("Eligible to drive."); // Output: Eligible to drive. } else { System.out.println("Not eligible to drive."); } } }

2. Logical OR Operator (||)

The logical OR operator returns true if at least one of the operands (conditions) is true; otherwise, it returns false.

Example:

public class LogicalOrExample { public static void main(String[] args) { boolean condition1 = true; boolean condition2 = false; // Using the logical OR operator boolean result = condition1 || condition2; // Evaluates to true System.out.println("Condition1 OR Condition2: " + result); // Output: Condition1 OR Condition2: true // Example in a conditional statement int age = 15; boolean hasPermission = false; if (age < 18 || hasPermission) { System.out.println("Not eligible to vote."); // Output: Not eligible to vote. } else { System.out.println("Eligible to vote."); } } }

3. Logical NOT Operator (!)

The logical NOT operator inverts the value of a boolean expression. If the expression is true, it becomes false, and vice versa.

Example:

public class LogicalNotExample { public static void main(String[] args) { boolean condition = true; // Using the logical NOT operator boolean result = !condition; // Evaluates to false System.out.println("Not Condition: " + result); // Output: Not Condition: false // Example in a conditional statement boolean isMember = false; if (!isMember) { System.out.println("You need to sign up."); // Output: You need to sign up. } else { System.out.println("Welcome back!"); } } }

Summary

Logical operators in Java are crucial for controlling the flow of your programs based on multiple conditions. They allow you to create complex logical statements in your conditional expressions. Understanding how to use logical operators effectively helps you build more sophisticated decision-making processes in your code.