Java Logical Operators in Conditions

Java Logical Operators in Conditions

Logical operators in Java are used to combine multiple conditions (boolean expressions). They help in making decisions during program execution.


List of Logical Operators

Operator Name Description Example
&& Logical AND True only if both conditions are true (a > b && a > c)
Logical OR
! Logical NOT Reverses the boolean value !(a > b)

1️⃣ Logical AND (&&)

Returns true only when both conditions are true.

Example:

public class Main {
public static void main(String[] args) {
int age = 20;

if(age >= 18 && age <= 60) {
System.out.println("Eligible for job");
} else {
System.out.println("Not eligible");
}
}
}

📌 Output:

Eligible for job

2️⃣ Logical OR (||)

Returns true if at least one condition is true.

Example:

public class Main {
public static void main(String[] args) {
int marks = 45;

if(marks >= 35 || marks == 30) {
System.out.println("Pass or Grace Marks Allowed");
} else {
System.out.println("Fail");
}
}
}

📌 Output:

Pass or Grace Marks Allowed

3️⃣ Logical NOT (!)

Reverses the result of the boolean condition.

Example:

public class Main {
public static void main(String[] args) {
boolean isRaining = false;

if(!isRaining) {
System.out.println("You can go outside");
} else {
System.out.println("Stay home");
}
}
}

📌 Output:

You can go outside

✔ Combining Logical Operators

You can combine multiple conditions using &&, ||, and !.

public class Main {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;

if(age >= 18 && hasLicense || age > 60) {
System.out.println("Allowed to Drive");
} else {
System.out.println("Not Allowed");
}
}
}


Short-Circuit Behavior

  • && stops checking if first condition is false

  • || stops checking if first condition is true

Example:

int a = 10;

if (a > 5 && a < 15) {
System.out.println("Condition true!");
}


🧠 Summary

Operator Works When Result
&& Both conditions true True
! Opposite of condition True/False reversed

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *