Demonstrate Logical Operators in Java
Problem
Logical operators (&& || !) combine or invert boolean values to build compound conditions out of simpler ones.
Given two boolean values, print the result of combining them with AND, OR, and NOT.
Java Program
public class DemonstrateLogicalOperators {
public static void main(String[] args) {
boolean x = true;
boolean y = false;
System.out.println(x + " && " + y + " = " + (x && y));
System.out.println(x + " || " + y + " = " + (x || y));
System.out.println("!" + x + " = " + (!x));
System.out.println("!" + y + " = " + (!y));
}
}Output
Core Logic
Applying AND, OR, and NOT to the same pair of booleans shows how each combines or inverts truth values differently.
- 1
xholdstrueandyholdsfalse. - 2
x && y(AND) istrueonly when both operands aretrue— here it'sfalse, sinceyisn't. - 3
x || y(OR) istruewhen at least one operand istrue— here it'strue, because ofx. - 4
!xand!y(NOT) simply flip a single boolean to its opposite value.
x = true and y = false: x && y is false, x || y is true, !x is false, and !y is true.Key Point: && and || both short-circuit — if the left operand alone already determines the result, the right operand is never evaluated at all.
Key Concepts
Approach 2: Java 8
import java.util.function.BiPredicate;
import java.util.function.UnaryOperator;
public class LogicalOperatorsLambda {
public static void main(String[] args) {
boolean x = true;
boolean y = false;
// Each operator is stored as a named, reusable lambda
BiPredicate<Boolean, Boolean> and = (p, q) -> p && q;
BiPredicate<Boolean, Boolean> or = (p, q) -> p || q;
UnaryOperator<Boolean> not = p -> !p;
System.out.println(x + " && " + y + " = " + and.test(x, y));
System.out.println(x + " || " + y + " = " + or.test(x, y));
System.out.println("!" + x + " = " + not.apply(x));
System.out.println("!" + y + " = " + not.apply(y));
}
}
Output
Core Logic
Wrapping && and || in named BiPredicates, and ! in a named UnaryOperator, turns each logical operator into a reusable value instead of an inline expression.
- 1
BiPredicate<Boolean, Boolean> and = (p, q) -> p && q;andBiPredicate<Boolean, Boolean> or = (p, q) -> p || q;store the AND and OR logic as lambdas. - 2
UnaryOperator<Boolean> not = p -> !p;stores the NOT logic the same way, taking one boolean instead of two. - 3
and.test(x, y)andor.test(x, y)call the two-argument lambdas;not.apply(x)calls the one-argument one. - 4Each result is printed with the same label as the direct version.
x = true and y = false: and.test(x, y) is false, or.test(x, y) is true, not.apply(x) is false, and not.apply(y) is true.Key Point: BiPredicate<Boolean, Boolean> is the standard functional interface for a two-argument boolean test — Java has no dedicated 'BooleanBinaryOperator', so BiPredicate fills that role.