Java Relational Operators

In the last lesson you learned about Java assignment operators. To answer questions like “is the user old enough?”, Java gives you comparison operators. They look at two values and give back one answer: true or false.

🤔 Why compare values?

A program that cannot compare is just a calculator. It can add, but it can never choose. To decide anything, it must compare two values first.

  • Apps compare all the time: YouTube checks if you are old enough, a bank checks if your balance is enough.
  • A comparison looks at two values and gives back a boolean (true or false).
  • An if statement then reads that boolean and picks what to do next.
  • These are also called relational operators, because they tell you the relation between two values. Same thing, two names.

We cover if fully in the next module. For now, focus on the comparing.

⚖️ The six comparison operators

Java has six operators for comparing two values.

Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 3 <= 5 true

Notice right away:

  • == is two equals signs, not one. One sign means assign, a different job (trap coming below).
  • >= and <= always put the equals sign second. There is no => or =<, and the wrong way will not compile.
  • != reads as “not equal”. The ! means “not” all over Java.

Each line below compares two numbers and prints the result.

int a = 5;
int b = 3;
System.out.println(a == b); // are they equal? -> false
System.out.println(a != b); // are they different? -> true
System.out.println(a > b); // is a bigger? -> true
System.out.println(a < b); // is a smaller? -> false
System.out.println(a >= 5); // a at least 5? -> true
System.out.println(b <= 3); // b at most 3? -> true

Read each one out loud to check your logic:

  • a == b asks “are they equal?” -> false, since 5 is not 3.
  • a != b asks “are they different?” -> true.
  • a >= 5 asks “is a at least 5?” -> true, since a is exactly 5 and “or equal to” counts.
  • The boundary value still passes with >=/<=. So 5 >= 5 is true, but 5 > 5 is false. This small difference causes many bugs.

Output

false
true
true
false
true
true

🎯 Comparison in a decision

A comparison alone just prints true or false. The power comes when you feed that boolean into an if to choose an action. Here is an age check.

int age = 20;
if (age >= 18) {
System.out.println("You can enter");
} else {
System.out.println("Too young");
}

Step by step:

  • Java looks at the comparison age >= 18.
  • age is 20, and 20 is at least 18, so it gives true.
  • The if sees true and runs the first block.
  • The else block is skipped.

The pattern: the comparison asks the question, the if acts on the answer.

Output

You can enter

⚠️ The == versus equals() trap for strings

This is the single biggest comparison mistake in Java, and it catches almost everyone once.

  • For numbers, == works perfectly. A number like 5 is a primitive: it holds the value right there, so == compares values directly.
  • A String is an object, not a primitive. The variable holds a reference (think: the address of a house where the text lives).
  • So for two strings, == compares the two addresses, not the text. It asks “same house?”, not “same furniture inside?”.
  • Two different objects can hold the same text, so == can say false even when the words match.

To compare the text, use .equals(). It walks through the characters and checks if they match.

String first = "hello";
String second = "hello";
System.out.println(first.equals(second)); // ✅ checks the text -> true

This asks “is the text the same?” -> true, because both hold "hello". This is the correct way to compare strings.

Output

true

Now see why == is dangerous. The next example forces Java to make a brand new object in memory.

String name1 = "Alex";
String name2 = new String("Alex"); // a fresh object, same text
System.out.println(name1 == name2); // ❌ compares addresses -> false
System.out.println(name1.equals(name2)); // ✅ compares the text -> true

Both strings say "Alex". But == gives false (different addresses), while .equals() gives true (same text).

Output

false
true

Why does == sometimes seem to work on strings?

  • Plain text like "hello" in your code gets reused by Java to save memory (the string pool), so == may give true by luck.
  • That luck runs out when strings come from user input, a file, or new String(...), leaving a silent bug. Never rely on it.

Never use == to compare string text

For strings, == compares object addresses, not the actual text. It can return false even when the words match. Always use .equals() to compare what two strings say. The same rule applies to other objects too, not just strings.

🔢 Comparing decimals can fool you

A second trap: comparing double or float with == can give the wrong answer even when the numbers should match.

  • A double cannot store most decimals exactly. The computer uses binary, and decimals like 0.1 have no exact binary form.
  • Tiny rounding errors creep in, so the value is almost right but not perfect.
  • == demands perfect, so it says false.

This example adds 0.1 three times and checks against 0.3.

double sum = 0.1 + 0.1 + 0.1;
System.out.println(sum); // prints something like 0.30000000000000004
System.out.println(sum == 0.3); // ❌ surprising -> false

The math says 0.3, but the stored value is a hair off.

Output

0.30000000000000004
false

The fix: stop asking “exactly equal?” and ask “close enough?”.

  • Pick a tiny tolerance, then check if the gap between the numbers is smaller than it.
  • Math.abs() gives the gap as a positive number, so direction does not matter.
double sum = 0.1 + 0.1 + 0.1;
double tolerance = 0.0000001; // a very small allowed gap
if (Math.abs(sum - 0.3) < tolerance) {
System.out.println("Close enough, treat as equal"); // ✅ this runs
} else {
System.out.println("Really different");
}

The gap is far smaller than our tolerance, so the program treats them as equal.

Output

Close enough, treat as equal
  • >, <, >=, and <= are usually fine with doubles, since a hair off rarely flips a “bigger than” answer.
  • Only == and != on decimals are risky. The tolerance trick is the standard fix.

🔤 Comparing characters

You can compare a char too, once you know the rule.

  • Java stores each character as a number, its Unicode value: 'A' is 65, 'B' is 66, 'a' is 97.
  • Comparing two chars really compares those numbers, so 'A' < 'B' is true (65 less than 66).
  • This is how programs sort names into alphabetical order.
char first = 'A';
char second = 'B';
System.out.println(first < second); // 65 < 66 -> true
System.out.println('a' == 97); // 'a' is 97 -> true
System.out.println('z' > 'a'); // 122 > 97 -> true

The middle line is the eye-opener: a char and an int compare directly, because the char becomes its number first. So 'a' == 97 is true.

Output

true
true
true

Remember: uppercase and lowercase are different numbers, so 'A' does not equal 'a'. To treat them the same, convert the case first (covered in the strings lessons).

⚠️ Common Mistakes

The comparison errors people hit most.

Using = instead of ==. A single = assigns; a double == compares. Inside an if, you want ==. Java usually refuses to compile if (score = 100) for numbers, but train your eyes to see two signs.

int score = 100;
// ❌ Avoid: a single = tries to assign, not compare
// if (score = 100) { ... }
// ✅ Good: a double == compares
if (score == 100) {
System.out.println("Perfect score");
}

Using == to compare string text. As we saw above, == checks object addresses, not words. Use .equals() for strings.

String input = new String("yes");
// ❌ Avoid: compares objects, can be false even when text matches
// if (input == "yes") { ... }
// ✅ Good: compares the actual text
if (input.equals("yes")) {
System.out.println("Confirmed");
}

Comparing doubles with ==. Rounding errors make exact equality unreliable. Use a small tolerance instead.

double price = 0.1 + 0.2; // not exactly 0.3 inside the computer
// ❌ Avoid: may be false because of tiny rounding errors
// if (price == 0.3) { ... }
// ✅ Good: check the gap against a tiny tolerance
if (Math.abs(price - 0.3) < 0.0000001) {
System.out.println("Equal enough");
}

Writing => or =<. It is always >= and <=, with the equals sign second. The other way around will not compile.

✅ Best Practices

  • Use == for primitives, .equals() for objects. Numbers, booleans, and chars use ==; strings and other objects use .equals(). This prevents the most common bug in the lesson.
  • Avoid == and != on doubles. Compare with a small tolerance using Math.abs(). Use >, <, >=, <= freely; they are reliable for decimals.
  • Read comparisons out loud. “age greater than or equal to 18” should match what you wrote.
  • Watch the boundary. >= 18 lets 18 in, but > 18 keeps 18 out. Off-by-one bugs hide here.
  • Keep conditions simple. One clear comparison beats a tangle. We combine them with logical operators next.

🧩 What You’ve Learned

  • ✅ Comparison operators check two values and return a boolean (true or false).
  • ✅ The six are ==, !=, >, <, >=, and <=, and >=/<= always put the equals sign second.
  • ✅ Comparisons feed into if statements to drive decisions.
  • ✅ For strings and other objects, use .equals() to compare the contents, never ==.
  • ✅ Avoid == on doubles; compare them with a small tolerance instead.
  • ✅ A char comparison really compares its Unicode number.
  • ✅ Do not confuse = (assign) with == (compare).

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What do comparison operators return?

    Why: Every comparison gives back a boolean: true or false.

  2. 2

    Which operator means 'not equal to'?

    Why: != means not equal to. So 5 != 3 is true.

  3. 3

    How should you compare the text of two strings?

    Why: Use .equals() to compare string text. == compares object addresses, not the actual text.

  4. 4

    Why is double a == double b risky?

    Why: Doubles store many decimals with tiny rounding errors, so == can be false even when the math should match. Compare with a small tolerance instead.

🚀 What’s Next?

You can compare two values now. But real decisions often need more than one check at once, like “age is over 18 AND the user agreed to the terms”. For that, you combine comparisons with logical operators. Let’s learn them next.

Java Logical Operators

Share & Connect