How to compare Strings in java

We can compare Strings in java either using == or equals() depending on how the String was created.

Using == to compare Strings in java

== operator will check the reference of the Strings. If the references are same then == will result in true.
The == can be only used when Strings are created from String Pool as shown in below code snippet.

As both the String in above code used String Pool, their reference will be same, hence the result of comparision would be true.

Using equals() method to compare Strings in java

If the Strings were created using new operator, then we need to use equals() method to compare the strings. if we try to compare these String using == , the result will be false, as the references of these Strings will be different.
equals() method compares the value of the String.

Complete Code Example


For comparing Strings ignoring the case consideration you can use public boolean equalsIgnoreCase(String anotherString) method of String.


1.String equals API