How to compare strings in java
equals()
and equalsIgnoreCase()
are the couple of methods that are widley used by any java developer.
Its a common question usually developers ask why we need these methods when we have the comparison operator "==" already in place.
In this blog, we are trying to understand different methods used to compare objects and its correct usage.
int x = 10;
int y = 10;
System.out.println(x == y);
--Output--
true
Yes, x == y
returns true
as expected as the values of both x
and y
are the same.
Let's see this example.
String x = "Hi";
String y = "Hi";
String z = new String("Hi");
System.out.println(x == y);
System.out.println(x == z);
--Output--
true
false
Even though, x, y and z are having the same string value, z
is not same as x and y
.
If you see here, ==
actually looking for the object equality.
Here the variables x
and y
are referring the same string "Hi", but z
is pointing to another String object that has the same value "Hi".
Here the importance of the methods equals()
and equalsIgnoreCase()
will come into picture.
true
if the given object represents a String equivalent to this string, false
otherwise.
String x = "Hi";
String y = "Hi";
String z = new String("Hi");
System.out.println(x.equals(y);
System.out.println(x.equals(z));
--Output--
true
true
How "==" and .equals() handle NULL?
==
will always evaluate to true
when you compare two strings that are null
.
But equals()
will throw NullPointerException
if the comparing strings or at least the caller string is null
.
if(Objects.nonNull(str1) {
str1.equals(str2);
})
What intern() is doing?
Calling intern()
on a string will return a canonical representation of the string object.
The String
class is maintaining a string pool internally and new strings will be inserted into this pool. Reference to an existing string will be made available from this private pool.
When the intern() method is invoked, String
will return the given string's representation from this pool, if exists. Otherwise a new string will be added to the pool and the same will be returned.
intern()
on one of the string variable.
String x = "Hi";
String y = "Hi";
String z = new String("Hi");
System.out.println(x == y);
System.out.println(x == z)
System.out.println(x == z.intern());
--Output--
true
false
true
Conclusion
- » We have learnt the difference between "==" and the equals() method.
- » How "==" and .equals() handle NULL.
- » What intern() method is doing.