Java comparing strings

In the last topic we have learnt Concatenating Strings in Java. In this chapter we are looking another String operation in Java Programming i.e Comparing two Strings. There are three ways for comparing the two strings.

NoComparing Strings
Way 1Using equals() method
Way 2Using == Operator
Way 3Using compareTo() method

Way 1 - Java Comparing Strings Using : equal() method

String Class provides us two different methods for comparison i.e -

public boolean equals(Object another){}
public boolean equalsIgnoreCase(String Str2){}

If we need to compare the content only then we can use 1st method specified above and if we need to compare the strings and cases both then we can use 2nd method. Below are the examples for using both the methods -

class ComparingString{
 public static void main(String args[]){
   String str1="c4learn.com";
   String str2="c4learn.com";
   String str3="C4LEARN.com";
   System.out.println(str1.equals(str2));//true
   System.out.println(str1.equals(str3));//false
   System.out.println(str2.equalsIgnoreCase(str3));//true
 }
}

Output :

true
false
true

Way 2 - Java Comparing Strings : Reference Comparison (==)

class ComparingString{
 public static void main(String args[]){
   String str1 = "c4learn.com";
   String str2 = "c4learn.com";
   String str3 = new String("c4learn.com");
   System.out.println(str1 == str2);//true
   System.out.println(str1 == str3);//false
 }
}

Consider the above example - In the below statement

System.out.println(str1 == str2);

str1 and str2 both are referring the same object. Which makes str1 and str2 equal. While in case of 2nd line -

System.out.println(str1 == str3);

Though content of str1 and str3 is same, instance of str3 is not same as that of str1. str3 refers to the instance that is created in the non-pool / heap.

Way 3 - compareTo() method

compareTo() method returns the integer which tells us the comparison status -

Result of ComparisonReturn Value
str1 = str20
str1 > str21
str1 < str2-1
Consider the following code snippet -

class ComparingString{
 public static void main(String args[]){
   String str1 = c4learn.com;
   String str2 = c4learn.com;
   String str3 = google.com;
   System.out.println(str1.compareTo(str2));//0
   System.out.println(str1.compareTo(str3));//1
   System.out.println(str3.compareTo(str1));//-1
 }
}

Output :

0
1
-1