How do I compare strings in Java?
Wondering how to compare strings in Java? This guide explains different ways to compare strings, including equals(), ==, and compareTo(), and when to use each method.
If you’re new to Java, you might be wondering how to compare strings properly. Unlike primitive types like int or double, strings in Java are objects, so you can’t always compare them with ==. Here are some common and effective ways to compare strings in Java:
Using equals() method (Best for content comparison)
The equals() method compares the actual content (characters) of two strings. This is the most reliable way to check if two strings are the same.
String str1 = "Hello";
String str2 = "Hello";
if (str1.equals(str2)) {
System.out.println("Strings are equal!");
}
Using == operator (Checks memory reference)
The == operator checks if both strings point to the same memory location. It doesn’t compare the actual content, so it might not always work as expected.
String str1 = new String("Hello");
String str2 = new String("Hello");
if (str1 == str2) {
System.out.println("Strings are equal!"); // This won’t print because `==` checks references.
}
Using compareTo() method (Lexicographical comparison)
This method compares strings based on dictionary order. It returns 0 if the strings are equal, a positive number if the first string is greater, and a negative number if it’s smaller.
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
System.out.println(result); // Outputs a negative number because "apple" comes before "banana".
In most cases, you should stick with equals() for content comparison. The compareTo() method is useful when sorting strings lexicographically, like in alphabetical order!