Operators
Java Program to Demonstrate Logical Operators
A Java program to demonstrate the usage of logical operators.
Problem Description
Write a Java program to demonstrate the usage of logical operators: AND (&&), OR (||), and NOT (!).
Code
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b: " + (a && b));
System.out.println("a || b: " + (a || b));
System.out.println("!a: " + (!a));
System.out.println("!b: " + (!b));
}
}Output
a && b: false
a || b: true
!a: false
!b: trueExplanation
&&(Logical AND): Returns true if both operands are true.||(Logical OR): Returns true if at least one operand is true.!(Logical NOT): Reverses the boolean value of the operand.
Try Yourself
- Combine Operators: Evaluate
(5 > 3) && (8 > 5). Is it true or false? - Short Circuit: In
false && (5 / 0 == 0), does the division by zero cause an error? Why or why not? - De Morgan's Laws: Is
!(A && B)the same as!A || !B? Write a code to verify. - Three Conditions: Check if a number
nis between 10 and 20 (inclusive). Hint:n >= 10 && n <= 20 - Brain Twister: What is the result of
true || false && false? (Check operator precedence).
