Comparison
- Java course
- Beginner
- Lesson 25/116
- 4 min
Learn ==, !=, <, >, <=, >= operators.
Comparison operators
Comparison operators compare two values and return a boolean (true or false). Java has six:
==equal!=not equal<less than>greater than<=less or equal>=greater or equal
int age = 18;
System.out.println(age >= 18); // true
System.out.println(age != 18); // falseYou can use the results in if conditions.
Practice Print comparison results
Write a Main class with a main method. Assign 10 to int x. Print x == 10 and x < 5 on separate lines with println.
Sample solution
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println(x == 10);
System.out.println(x < 5);
}
}Expected output
true false
Equality == vs assignment =
In Java == does equality comparison, while = does assignment. They are often confused.
int a = 5; // assignment: a is set to 5
if (a == 5) // comparison: is a equal to 5?For Strings, == compares references; to compare content use equals. For numbers, == compares values directly.
Accidentally writing = can give a compile error or a logic bug.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the operators
| Term | Meaning |
|---|---|
== |
Equal |
!= |
Not equal |
< |
Less than |
>= |
Greater or equal |
2 What is the result of 5 != 3?
- true Correct answer
- false
- 5
- 3
Explanation: 5 is different from 3, so true.
3 Complete the comparison
boolean greater = 7 ____ 5;
boolean greater = 7 > 5;
Explanation: Greater-than comparison uses >.