Lesson 2 of 514 minModule progress 0%

Module 3: Operators, Expressions, and Strings

Comparison and Logical Operators

Compare values and combine true/false results with logical operators so you are ready for conditions in the next module.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-16

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, edited by hand, and checked against current Java 25 documentation and runnable examples.

Learning goals

  • Use comparison operators such as `==`, `!=`, `>`, and `<`
  • Combine boolean expressions with `&&`, `||`, and `!`
  • Read simple true/false results confidently

Comparison operators: Use ==, !=, >, <, >=, and <= to compare values.

Logical operators: Use && when both conditions must be true, || when either can be true, and ! to invert a boolean value.

Why this matters: These operators are the building blocks for if, else if, switch, and input validation.

Read them aloud: Saying an expression in plain English often helps. For example, age >= 18 && hasId reads as "age is at least 18 and hasId is true."

Runnable examples

Comparison results

public class Main {
    public static void main(String[] args) {
        int age = 20;
        System.out.println(age >= 18);
        System.out.println(age == 21);
    }
}

Expected output

true
false

Logical operators

public class Main {
    public static void main(String[] args) {
        boolean hasTicket = true;
        boolean hasId = false;
        System.out.println(hasTicket && hasId);
        System.out.println(hasTicket || hasId);
    }
}

Expected output

false
true

Common mistakes

Using `=` instead of `==` when comparing values

Use `==` for comparison and `=` for assignment.

Mini exercise

Create two boolean variables and print the results of `&&` and `||` with them.

Summary

  • Comparison operators produce booleans.
  • Logical operators combine booleans into larger conditions.

Next step

Now use strings to print richer messages and work with text more comfortably.

Sources used

Advertisement

Lesson check

Which operator means "both conditions must be true"?

Next lesson →