Java Comparison Operators

Comparison operators ask questions about two values and always answer with a boolean, either true or false. They are the backbone of decision-making in Java, feeding directly into if statements and loops.

The six comparison operators

Each comparison operator takes two operands and returns a boolean. The table below lists all six, with a sample result assuming a is 8 and b is 5.

OperatorNameExample (a=8, b=5)Result
==Equal toa == bfalse
!=Not equal toa != btrue
>Greater thana > btrue
<Less thana < bfalse
>=Greater than or equal toa >= 8true
<=Less than or equal tob <= 5true

Storing comparison results

Because a comparison produces a boolean, you can store it in a boolean variable and print it, or use it directly. Beginners often forget that these operators return a value rather than doing anything on their own.

Comparisons produce booleans

public class Main {
  public static void main(String[] args) {
    int age = 20;

    boolean isAdult = age >= 18;
    boolean isTeenager = age < 13;

    System.out.println(isAdult);    // true
    System.out.println(isTeenager); // false
  }
}

Comparisons inside an if statement

The most common place you will use comparisons is inside an if statement, where Java runs a block of code only when the condition is true. Here we check whether a score passes a threshold.

Driving a decision

public class Main {
  public static void main(String[] args) {
    int score = 72;

    if (score >= 50) {
      System.out.println("Pass");
    } else {
      System.out.println("Fail");
    }
    // prints: Pass
  }
}
Note: Do not use == to compare the contents of two String objects. For text, use the equals() method, as in name.equals("Sam"). The == operator checks whether they are the same object in memory, which is rarely what you want.
Note: Comparison operators only give a single true or false. To combine several conditions, such as checking a number is between two bounds, you pair them with the logical operators covered next.