Comparison operators
20 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A comparison operator compares two values and gives a boolean answer: true or false. For example, marks >= 35 is true when a student has passed.
The six comparison operators
An exam app must tell each student whether they passed: a yes-or-no answer, not another number.
A comparison gives exactly that: marks >= 35 is true for 42 marks and false for 30. These are also called relational operators.
Example 1 · Store the answer in a boolean
public class Eligibility { public static void main(String[] args) { int attendance = 72; boolean canSitExam = attendance >= 75; System.out.println("Can sit exam: " + canSitExam); double balance = 450.0; double price = 499.0; boolean canBuy = balance >= price; System.out.println("Can buy: " + canBuy); }}Can sit exam: false Can buy: false
What this code does
- A comparison gives a
boolean, from char and boolean (opens in a new tab), soattendance >= 75can go straight intocanSitExam. - Comparisons work on
doublevalues too: 450.0 is less than 499.0, socanBuyisfalse.
Java has six of them: == equal to, != not equal to, > greater than, < less than, >= greater than or equal to, and <= less than or equal to. Move the sliders below to try all six.
Experiment
Compare
Move a and b. Make them equal and watch which answers change.
- a > b
- true
- a < b
- false
- a >= b
- true
- a <= b
- false
- a == b
- false
- a != b
- true
>= and <= with no space, and with = second. => and =< are not Java operators.== asks, = stores
You want to check for full marks, so you type boolean isFull = (marks = 100);. Java refuses to compile it.
int marks = 100;boolean isFull = (marks = 100); // error: incompatible types: int cannot be converted to booleanboolean isTop = (marks == 100); // trueOne = stores a value. Two, ==, ask whether two values are equal. marks = 100 asks nothing, so its answer is an int, not a boolean.
Comparing text: use equals()
A login screen checks whether the typed username is "admin". With text, == can say false even when every letter is the same.
To compare the text of two Strings, use equals(): user.equals("admin") gives true or false.
Example 2 · Text: equals() and ==
public class TextCompare { public static void main(String[] args) { String first = "Ra"; String name = first + "vi"; System.out.println(name); System.out.println(name.equals("Ravi")); System.out.println(name == "Ravi"); }}Ravi true false
What this code does
nameholds the textRavi, andequals()correctly saystrue.==saysfalse:namewas built while the program ran, so it is a different object from"Ravi".
On a String, == asks a different question: are both variables the very same object in memory? Compare Strings: equals() and compareTo() (opens in a new tab) explains the memory side later in the course.
== is right for numbers, char and boolean. To compare String text, use equals().Next step
Check your understanding
10 quick questions