AI Hints
Home›Java Tutorial›Comparison Operators, if, else and else if
Java · Lesson 28 of 120

Comparison Operators

Asking questions.

⏱ 2 min read▶ Video at 36:34🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Programs make decisions by asking questions. Is the age at least eighteen? Is the password right? Each question has a yes or no answer, a boolean.

  • Programs ask questions
  • Yes or no
  • A boolean answer

The six comparisons

Two equals signs means is equal to. Exclamation mark equals means not equal. Then greater than, and less than. And with an equals sign after them, greater or equal, and less or equal.

OperatorMeans
==equal to
!=not equal to
> <greater than, less than
>= <=greater or equal, less or equal

Comparisons give booleans

Age is eighteen. Each comparison gives true, or false. A comparison can also be stored in a boolean variable. Run it. Equal, true. Not equal, false. And adult is true, because eighteen is at least eighteen.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int age = 18;
        System.out.println("age == 18  " + (age == 18));
        System.out.println("age != 18  " + (age != 18));
        System.out.println("age > 21   " + (age > 21));
        System.out.println("age < 21   " + (age < 21));
        System.out.println("age >= 18  " + (age >= 18));
        System.out.println("age <= 17  " + (age <= 17));
        boolean adult = age >= 18;
        System.out.println("adult: " + adult);
    }
}
Output
age == 18  true
age != 18  false
age > 21   false
age < 21   true
age >= 18  true
age <= 17  false
adult: true

One or two equals

One equals sign stores a value. Two equals signs compare values. Mixing them up is a very common mistake. And remember, for strings, use equals, not two equals signs.

keyvalue
=store a value
==compare values
Stringsuse .equals()
Resultalways a boolean

Summary

Comparison operators ask yes or no questions, and give back a boolean. Next, using those answers, with if.

Key takeaways
  • == != > < >= <=
  • Give true or false
  • = stores, == compares
Next up: if — run code only sometimes