Comparison and Logical Operators

Comparison Operators

Comparison operators compare two values and return a boolean.

OperatorMeaningExample (a=10, b=20)Result
==equal toa == bfalse
!=not equala != btrue
>greater thana > bfalse
<less thana < btrue
>=greater or equala >= 10true
<=less or equalb <= 15false

Logical Operators

OperatorNameTrue when
&&ANDboth sides are true
||ORat least one side is true
!NOTreverses 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;