How do I compare strings in Java?

I’m confused about the different ways to compare strings in Java. When should I use == and when should I use .equals() or .compareTo()? I want to understand how string comparison actually works and which method is best for different scenarios.

In Java, strings should be compared using methods, not the == operator (in most cases). The == operator checks reference equality (whether both variables point to the same object), not the actual string content.

The correct and commonly used way is equals(), which compares the content of two strings:

String a = "Java";
String b = "Java";
a.equals(b); // true

If you want a case-insensitive comparison, use equalsIgnoreCase():

a.equalsIgnoreCase("java"); // true

To compare strings lexicographically (alphabetical order), use compareTo():

a.compareTo("Python"); // returns a positive or negative value

Use == only when you intentionally want to check if both references point to the same object. For most real-world cases, equals() is the correct and safe choice.


1 Like

I was confused about this too when I started with Java. The key thing to remember is == vs .equals() vs .compareTo() do different things.

  • ==
String a = "hello";
String b = "hello";
System.out.println(a == b); // true sometimes, but not always

This checks if both references point to the same object, not if the content is the same. So it can be tricky and usually not what you want for strings.

  • .equals()
System.out.println(a.equals(b)); // true

This checks if the actual text/content of the strings is the same. Most of the time, this is what you should use for string comparison.

  • .compareTo()
String a = "apple";
String b = "banana";
System.out.println(a.compareTo(b)); // negative value because "apple" < "banana"

This is used when you want to compare lexicographically (like dictionary order). Returns 0 if equal, <0 if first is smaller, >0 if first is bigger. Useful for sorting.

1 Like