ESC
Type to search...
Dashboard / Java notes / Concepts / Basics / Part i

04 - Comparison

P1 · Updated · Source
#java/basics #l0 #concept #must-know #status/known

Comparison & Equality

What is it?

Comparison lets you check a relationship between two values. The result is always a boolean - either true or false. This is what makes decision-making (if statements) possible.

Comparison Operators

Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 7 > 3 true
< Less than 3 < 7 true
>= Greater than or equal 5 >= 5 true
<= Less than or equal 4 <= 3 false
int a = 10;
int b = 20;

System.out.println(a == b);  // false
System.out.println(a < b);   // true
System.out.println(a != b);  // true

The Big Rule: == does NOT work for Strings

== compares memory addresses, not content. Primitives (int, double, boolean) live directly in memory, so == works fine on them. But String is an object - a reference to a location in memory - so two strings with the same content might be stored at different addresses.

// Primitives - == works fine
int x = 5;
int y = 5;
System.out.println(x == y); // true ✅

// Strings - == is unreliable
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2);        // true in this case... but NOT reliable
System.out.println(s1.equals(s2));   // true ✅ always correct

Important Always use .equals() to compare Strings. Using == on Strings might sometimes work (due to Java’s string pool optimisation), but it will silently fail in other cases - especially with user input.

Comparing Strings - .equals() and .equalsIgnoreCase()

String input = scanner.nextLine();

// Case-sensitive comparison
if (input.equals("yes")) {
    System.out.println("User said yes");
}

// Case-insensitive comparison
if (input.equalsIgnoreCase("yes")) {
    System.out.println("User said yes (in any case)");
}

Boolean Variables

The result of a comparison can be stored in a boolean variable:

boolean isAdult = age >= 18;
boolean isMatch = name.equals("Alice");

System.out.println(isAdult); // true or false

Logical Operators - combining conditions

Operator Meaning Example
&& AND - both must be true age > 18 && hasID
\|\| OR - at least one must be true isAdmin \|\| isOwner
! NOT - flips true to false !isLoggedIn
int age = 20;
boolean hasTicket = true;

if (age >= 18 && hasTicket) {
    System.out.println("Access granted");
}

Gotchas

  • Using = instead of == inside a condition is a common bug: if (x = 5) is an assignment, not a comparison - Java will actually give a compiler error here, but in some languages it’s a silent bug
  • Comparing null with .equals() will throw a NullPointerException. To check for null: use variable == null (this is the one safe == use with objects)
  • >= and <= are two characters - no space between them

Related: Condition, String, Calculations