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.
1 2 3 |
String str1 = "Foo"; String str2 = "Foo"; System.out.println("Results for str1 == str2 :: "+ (str1 == str2)); |
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.
1 2 3 4 |
String str3 = new String("Foo"); String str4 = new String("Foo"); System.out.println("Results for str3 == str4 :: "+ (str3 == str4)); // false System.out.println("Results for str3.equals(str4) :: "+ (str3.equals(str4))); // true |
Complete Code Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.kscodes.sampleproject; public class StringComparisionExample { public static void main(String[] args) { String str1 = "Foo"; String str2 = "Foo"; String str3 = new String("Foo"); String str4 = new String("Foo"); System.out.println("Results for str1 == str2 :: "+ (str1 == str2)); System.out.println("Results for str1 == str3 :: "+ (str1 == str3)); System.out.println("Results for str3 == str4 :: "+ (str3 == str4)); System.out.println("Results for str1.equals(str2) :: " + (str1.equals(str2))); System.out.println("Results for str1.equals(str3) :: "+ (str1.equals(str3))); System.out.println("Results for str3.equals(str4) :: "+ (str3.equals(str4))); } } |
Output
1 2 3 4 5 6 |
Results for str1 == str2 :: true Results for str1 == str3 :: false Results for str3 == str4 :: false Results for str1.equals(str2) :: true Results for str1.equals(str3) :: true Results for str3.equals(str4) :: true |
For comparing Strings ignoring the case consideration you can use public boolean equalsIgnoreCase(String anotherString) method of String.