Relational & equality operators in Java
<, >, <=, >=, ==, != and comparing references vs values.
== says they're NOT equal. Is Java blind, or are we asking the wrong question?Comparisons make booleans
<, >, <=, >=, == (equal) and != (not equal) compare values. Every comparison produces a boolean: true or false, never 1 or 0.
5 < 7 // true
5 >= 6 // false
5 == 5 // true
5 != 7 // trueYour turn
What does this print?
int a = 3, b = 3;
System.out.println(a <= b);
System.out.println(a != b);true false1 0false false
Show the answer
3 <= 3 is true, and 3 != 3 is false. Comparisons print as booleans, not numbers.
Primitives: compare values
For primitives, == compares values, after promoting both sides to a common type. So 10 == 10.0 is true (10 becomes 10.0), and 'a' == 97 is true ('a' becomes 97).
Objects: the same object?
For objects, == asks "are these the very same object?" Two separate String objects with the same text are not ==. To compare content, use a.equals(b).
String a = "cat";
String b = "c";
b = b + "at"; // new object
a == b // false: 2 objects
a.equals(b) // true: same textYour turn
What does this print?
String s1 = "dog";
String s2 = "do";
s2 = s2 + "g";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));false truetrue truetrue false
Show the answer
s2 + "g" is built at runtime as a new String object. Same text, different objects: == is false, equals is true.
No chained comparisons
5 < 7 becomes true, and then true < 9 makes no sense: a boolean can't be compared with an int. Write 5 < 7 && 7 < 9.
System.out.println(5 < 7 < 9); // error
System.out.println(5 < 7 && 7 < 9);In real projects
if (input == "yes") is a classic beginner bug. It can even seem to work, then fail for text typed by a user or read from a file. Professionals compare Strings with equals, often as "yes".equals(input) to be null-safe.
Key takeaways
- Comparisons always produce a boolean
- == on primitives compares values (with promotion)
- == on objects compares references
- Use a.equals(b) for String content
Java keeps String literals in a shared "string pool", so "cat" == "cat" is true: both are the same pooled object. That's exactly why == seems to work... until it doesn't.
Practice questions
What does this print?
int a = 5, b = 7;
System.out.println(a < b);
System.out.println(a != b);- true false
- true true
- false true
- 1 1
Check your answer
true true. 5 < 7 is true and 5 differs from 7, so both comparisons are true. Comparisons produce booleans, not 1 or 0.
What does this print?
String a = "cat";
String b = "c";
b = b + "at";
System.out.println(a == b);
System.out.println(a.equals(b));- false true
- true true
- true false
- false false
Check your answer
false true. The concatenation runs at runtime and creates a new String object, so a and b are different objects with the same text.