How to compare strings in java?

String comparison means checking if the two strings are equal to each other or not. Comparing strings in java can be done in the following different ways-

Comparing two strings without using Library methods :-

String is a sequence of characters so if you want to compare two strings in java without using any library function then you can use the given logic.

First, check if the lengths of both the strings are equal. If the length of the strings are not equal, we will not check any further (since that means the strings are not equal), thus the efficiency of the program would increase. If they are equal then we compare each string character by character.

Following is the program to compare two strings without using in-built comparison functions-

import java.util.*;
class Main {
  public static void main(String args[]) {
    int i, flag = 1, len1, len2;
    String s1, s2;
    s1 = "Flowers";
    s2 = "flowers";
    len1 = s1.length();
    len2 = s2.length();
    
    if (len1 == len2) {
char str1[] = s1.toCharArray();
    char str2[] = s2.toCharArray();

      for (i = 0; i < len1; i++) {
        if (str1[i] != str2[i]) {
          flag = 0;
          break;
        }
      }
    } else {
      flag = 0;
    }
    if (flag == 1) {
      System.out.println(s1 + " is equal to " + s2);
    } else {
      System.out.println(s1 + " is not equal to " + s2);
    }
  }
}

The output of the above sample code will be-

flower is not equal to Flower   

Comparing strings using equals() method :-

The equals() method in java, compares the given strings based on the contents of the strings. It is case sensitive and compares each character of the String to each character of the other String. The equals() method returns a boolean value, it returns "false" if the strings are unequal and "true" if the strings are equal.

A point to be noted is that whether we write "s1.equals(s2)" or s2.equals(s1)", the result will be the same! You cannot use the equals() method on a null object.

Below is a sample program to compare two strings using the equals() method :-

class Main{  
 public static void main(String args[]){  
   String s1="Chercher";  
   String s2="cherCher";  
   String s3=new String("Chercher");
   String s4="CherCher";
   System.out.println(s1.equals(s2));//false 
   System.out.println(s1.equals(s3));//true  
   System.out.println(s1.equals(s4));//false  
 }  
}  

Output-

false
true
false

Comparing strings using equalsIgnoreCase() method :-

The equalsIgnoreCase() method compares two strings but is not case-sensitive i.e. "hello" and "HELLO" (Upper and lower case) will be considered equal and it will return "true". You have seen that the equals() method is case-sensitive and in the above case it will return "false".

So when you just want to check if the characters are the same regardless of their case then use the equalsIgnoreCase() method.

String s1 = "Hello";
String s2 = "heLLo";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));

So, the above code snippet's output will be-

false
true

Comparing strings using compareTo() method :-

The compareTo() method checks for the String's lexicographical value. If we compare two strings suppose str1 and str2, then if str1 has a lexicographical value higher than the value of str2, then the method will return a positive value, if it's lower, the method will return a negative value. If they're the same, the method will return 0.

String is a sequence of characters so we can compare them lexicographically. Comparing strings lexicographically means that each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns a positive or negative value.

Let us look at the example below to understand the compareTo() method more-

public class Main {
  public static void main(String[] args) {
    String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.compareTo(s2));

String s3 = "Welcome";
String s4 = "Welcome";
System.out.println(s3.compareTo(s4));
//comparing two null values
String s5 = "";
String s6 = "";
System.out.println(s5.compareTo(s6));

String s7="world";
String s8="word";
System.out.println(s7.compareTo(s8));

//the compareTo() method doesn't work the same if you swap the strings
//If the above result is positive then the below result would be negative
System.out.println(s8.compareTo(s7));
    
  }
}

The output generated will clarify to you how the method works-

-32
0
0
8
-8

So you can see that "s1.compareTo(s2)" is different from "s2.compareTo(s1)" unlike the equals() method where it works in the same way when you swap the strings.

Comparison of strings using compareToIgnoreCase() method-

Just like the equalsIgnoreCase() method, the compareToIgnoreCase() method does not care about the case of the characters. It works in the same way as the compareTo() method except for the fact that it is not case-sensitive. Example-

String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.compareToIgnoreCase(s2));

The output would be -32 like in the previous example, but here-

0
//since compareToIgnoreCase() does not care about case of characters 
//so it will mark them equal

Using contentEquals() method to compare strings-

The contentEquals() method compares CharSequence and StringBuffer. With this method, you don't have to convert a StringBuffer into String for comparison, the contentEquals() method will do that itself.

With the earlier methods, we can't compare String to StringBuffer, but with contentEquals() we can.

example-

String s1 = "tt";
StringBuffer s2 = new StringBuffer("");
for (int i = 0; i < 2; i++) {
    s2.append('t');
}
System.out.println(s1.contentEquals(s2));

The above code will return- true

Comparison of strings using StringUtils.equals() -

StringUtils is a helper class with various string related operations like StringUtils.equals() and StringUtils.equalsIgnoreCase. It works like the equals() method but null values cannot be compared with equals() method, but with StringUtils.equals() method null values can be compared i.e. it checks for null values as well.

String s1 = "Welcome";
String s2 = new String("Welcome");
System.out.println(StringUtils.equals(s1, s2));
System.out.println(StringUtils.equals(s1, null));
System.out.println(StringUtils.equals(null, null));

The output will be-

true
false
true

The StringUtils.equalsIgnoreCase() method works in the same way as above but does not care about the case of characters.

Using the StringUtils.equalsAny() method-

The equalsAny() method's first argument is a String and the second is a multi-arguments type CharSequence. The method returns true if any of the other given Strings match against the first String. It is case-sensitive. The equalsAnyIgnoreCase() method works similarly to the equalsAny() method, but also ignores casing.

example-

System.out.println(StringUtils.equalsAny("Hello World", "Hello", "World"));
System.out.println(StringUtils.equalsAny("Welcome", "welcome", "bye"));

The output will be-

true
false
Now can we use the "==" operator to compare strings?

The answer is that the "==" operator doesn't check for equality. It checks for identity. This means that while the equals() method checks the String values (content), the "==" operator compares object references (address comparison). This is why the "==" operator should be avoided to compare strings.

The below example will make it clear-

 public static void main(String[] args)
    {
        String str1 = new String("hello");
        String str2 = new String("hello");
        System.out.println(str1 == str2);
        System.out.println(str1.equals(str2));
     }        

Output-

false
true

Here two String objects are created as str1 and str2. Both str1 and str2 refer to different objects. When you use the "==" operator for comparison then the result is false as both have different addresses in memory. But when you use the equals() method, the result is true because it is only comparing the values (content) given in str1 and str2.

So these were the different ways to compare strings in java.

0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions