Core Java Fundamentals ยท Operators
Learn how to combine multiple boolean conditions using AND, OR, and NOT operators to create more complex decision-making logic.
public class LogicalOperatorsDemo {
public static void main(String[] args) {
// --- Setup ---
boolean isStudent = true;
int age = 25;
boolean isWeekend = false;
boolean isSenior = age >= 65;
// --- 1. AND (&&) Operator ---
System.out.println("--- AND Operator (&&) ---");
if (isStudent && !isWeekend) {
System.out.println("Student Weekday Discount Applied!");
} else {
System.out.println("No Student Weekday Discount.");
}
// --- 2. OR (||) Operator ---
System.out.println("--- OR Operator (||) ---");
if (isStudent || isSenior) {
System.out.println("General Discount Applied (Student or Senior)!");
} else {
System.out.println("No General Discount.");
}
// --- 3. NOT (!) Operator ---
System.out.println("--- NOT Operator (!) ---");
if (!isWeekend) {
System.out.println("It's a weekday!");
} else {
System.out.println("It's the weekend!");
}
// --- 4. Combining Operators & Precedence ---
System.out.println("--- Combining Operators ---");
if ((isStudent || isSenior) && !isWeekend) {
System.out.println("Premium Discount Conditions Met!");
} else {
System.out.println("Premium Discount Conditions Not Met.");
}
}
}isStudent and isWeekend are set directly, while isSenior will be calculated based on age.age >= 65 (25 >= 65) evaluates to false. This boolean value is assigned to the isSenior variable.&& operator. It returns true only if both conditions on its left and right are true.isStudent && !isWeekend. First, !isWeekend evaluates to !false, which is true. The condition becomes true && true, which is true. We will enter the if block.|| operator. It returns true if at least one of the conditions is true.isStudent || isSenior. Since isStudent is true, the JVM doesn't need to check isSenior. This is called "short-circuiting". The overall result is true.if block is executed because the condition was true.if block is executed because the condition was true.if block is executed because the condition was true.() are used to control the order of evaluation, just like in math. The expression inside the parentheses is evaluated first.() are used to control the order of evaluation, just like in math. The expression inside the parentheses is evaluated first.() are used to control the order of evaluation, just like in math. The expression inside the parentheses is evaluated first.(isStudent || isSenior) evaluates to (true || false), which is true.
2. !isWeekend evaluates to !false, which is true.
3. The final condition becomes true && true, which is true.