In Java, there are two ways to compare two strings: using the == operator and the equals() method.
It’s important to understand the difference between the two because they can produce different results.
The == operator is used to compare the memory addresses of two objects.
When used with strings, it compares whether two string objects point to the same memory location.
This means that if two strings have the same value, but they are created as two different objects, they will not be equal when compared using ==.
String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello"); System.out.println(str1 == str2); // true System.out.println(str1 == str3); // false
In this example, str1 and str2 are both pointing to the same object in memory, so comparing them with == returns true.
However, str3 is created as a new object using the
new keyword, so it points to a different memory location.
Therefore, comparing it with == returns false.
On the other hand, the equals() method is used to compare the values of two objects, regardless of whether they point to the same memory location or not.
When used with strings, it compares whether two string objects have the same sequence of characters.
String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello"); System.out.println(str1.equals(str2)); // true System.out.println(str1.equals(str3)); // true
In this example, comparing str1 and str2 with equals() returns true because they have the same value.
Comparing str1 and str3 with equals() also returns true, even though they are two different objects in memory.
It’s important to note that the equals() method is case-sensitive, so “Hello” and “hello” are considered different strings.
To perform a case-insensitive comparison, you can use the equalsIgnoreCase() method instead.
In summary, the == operator compares the memory addresses of two objects, while the equals() method compares their values.
When comparing strings, it’s usually more appropriate to use the equals() method because it compares their values.