AND, OR, NOT
| Operator | Name | True when... |
|---|---|---|
&& | AND | both sides are true |
|| | OR | at least one side is true |
! | NOT | flips true to false and false to true |
Think of it like this: “You can enter if you have a ticket AND you are 18+.” “You get a discount if you are a student OR a senior citizen.”
public class Main {
public static void main(String[] args) {
int age = 20;
boolean hasTicket = true;
if (age >= 18 && hasTicket) {
System.out.println("Welcome to the concert!");
}
boolean isStudent = false;
boolean isSenior = true;
if (isStudent || isSenior) {
System.out.println("You get a discount.");
}
boolean isRaining = false;
if (!isRaining) {
System.out.println("No umbrella needed.");
}
}
}Output
Welcome to the concert! You get a discount. No umbrella needed.
Checking a range
To check if a number is between two values, you need two comparisons joined with &&:
public class Main {
public static void main(String[] args) {
int hour = 14;
if (hour >= 9 && hour < 17) {
System.out.println("The shop is open");
} else {
System.out.println("The shop is closed");
}
}
}Output
The shop is open
Common mistake:
9 <= hour <= 17works in maths but not in Java. Writehour >= 9 && hour <= 17.