Logical operators help you combine or change true/false values to make decisions in your program.
0
0
Logical operators in Java
Introduction
Checking if two conditions are both true before doing something.
Deciding if at least one condition is true to proceed.
Making sure a condition is not true before continuing.
Combining multiple yes/no questions to control program flow.
Syntax
Java
condition1 && condition2 // AND operator condition1 || condition2 // OR operator !condition // NOT operator
&& means both conditions must be true.
|| means at least one condition must be true.
! reverses true to false, and false to true.
Examples
This checks if age is over 18 and the person has an ID.
Java
if (age > 18 && hasID) { System.out.println("Allowed to enter"); }
This checks if it is a weekend or a holiday.
Java
if (isWeekend || isHoliday) { System.out.println("No work today"); }
This checks if it is not raining.
Java
if (!isRaining) { System.out.println("Go outside"); }
Sample Program
This program uses logical operators to decide if someone can drive, if they can relax today, and if they should go for a walk.
Java
public class LogicalOperatorsDemo { public static void main(String[] args) { boolean hasLicense = true; int age = 20; if (age >= 18 && hasLicense) { System.out.println("You can drive."); } else { System.out.println("You cannot drive."); } boolean isWeekend = false; boolean isHoliday = true; if (isWeekend || isHoliday) { System.out.println("You can relax today."); } else { System.out.println("You have to work today."); } boolean isRaining = false; if (!isRaining) { System.out.println("Let's go for a walk."); } else { System.out.println("Better stay inside."); } } }
OutputSuccess
Important Notes
Remember that && stops checking if the first condition is false (short-circuit).
Similarly, || stops checking if the first condition is true.
Use parentheses to group conditions clearly when combining multiple logical operators.
Summary
Logical operators combine true/false values to control decisions.
&& means both must be true, || means one or both are true, ! reverses the value.
They help your program make smart choices based on multiple conditions.