Careeroza
Comparison and Logical Operators
Comparison Operators
Comparison operators compare two values and return a boolean.
| Operator | Meaning | Example (a=10, b=20) | Result |
|---|---|---|---|
== | equal to | a == b | false |
!= | not equal | a != b | true |
> | greater than | a > b | false |
< | less than | a < b | true |
>= | greater or equal | a >= 10 | true |
<= | less or equal | b <= 15 | false |
Logical Operators
| Operator | Name | True when |
|---|---|---|
&& | AND | both sides are true |
|| | OR | at least one side is true |
! | NOT | reverses true/false |
Example
public class Main {
public static void main(String[] args) {
int age = 25;
boolean hasLicence = true;
boolean isDrunk = false;
System.out.println(age >= 18 && hasLicence); // can drive
System.out.println(age < 18 || !hasLicence); // cannot drive
System.out.println(age >= 18 && hasLicence && !isDrunk);
System.out.println(age == 25);
System.out.println(age != 25);
}
}Output
true false true true false
Practice
Exercise: A user gets free delivery if the cart total is at least 499 or they are a Plus member. Write the boolean expression for double total and boolean isPlus.
Show answer
boolean freeDelivery = total >= 499 || isPlus;