Introduction to String Comparison in Java

A String is just a sequence of ordered characters in Java. A point to note is that strings are immutable objects in Java, so you can’t modify strings. It is one of the most commonly used objects in Java, and the comparison between strings is heavily used in Java. There can be a lot of scenarios where you might perform string comparisons in Java, such as sorting an array of strings or finding out verifying whether an input string already exists in the database or not. 

In this comprehensive guide, you will look at different ways through which one can compare strings in Java efficiently and quickly.

You will look at all the above methods for string comparison in-detail with hands-on examples for each of them. So without any further ado, it’s time to get started.

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

1. String Comparison using the Equality (==) Operator.

The equality operator in Java is used to compare two or more objects. If it finds out that both the objects points or refers to the same thing, it returns true, else false. Please note that the equality operator does not compare the actual value in Java, it only compares the references. In simpler words, when you define strings as objects, they won’t compare with the actual value but only the references. However, if you define strings directly with double-quotes, then you can compare the actual values stored inside them. Let’s verify both the scenarios using simple examples.

Example 1

class StringCompare{

   public static void main(String args[]){

       String s1 = "Hello";

       String s2 = "Hello";

       String s3 = "Welcome";

       if(s1==s2){

           System.out.println("Strings s1 and s2 are equal");

       }else{

           System.out.println("Strings s1 and s2 are not equal");

       }

       if(s1==s3){

           System.out.println("Strings s1 and s3 are equal");

       }else{

           System.out.println("Strings s1 and s3 are not equal");

       }

   }

}

In the example above, you have seen the creation of 3 string variables using double-quotes where s1 and s2 have the same string values which differ from the ones stored in s3. The aim is to check whether the values in s1 and s2 are the same or not, and also whether the values in s1 and s3 are equal or not. This example has simply used the equality operator along with if-else conditions to print the results. Let’s check out the output.

StringComparisonInJavaEx1

You can see that the outputs are correct. This means that the equality operator is working fine in this case. This is so because you have defined the strings using double-quotes here. Let’s create them as objects using a new operator in the next example.

Example 2

class StringCompare{

   public static void main(String args[]){

       String s1 = new String("Hello");

       String s2 = new String("Hello");

       String s3 = new String("Welcome");

       String s4 = s1;

       if(s1==s2){

           System.out.println("Strings s1 and s2 are equal");

       }else{

           System.out.println("Strings s1 and s2 are not equal");

       }

       if(s1==s3){

           System.out.println("Strings s1 and s3 are equal");

       }else{

           System.out.println("Strings s1 and s3 are not equal");

       }

       if(s4==s1){

           System.out.println("Strings s4 and s1 are equal");

       }else{

           System.out.println("Strings s4 and s1 are not equal");

       }

   }

}

In the above example, you can have initialized the strings as objects. Also, you have created a new string object called s4, which simply refers to s1. Let’s see the output of the above code.

StringComparisonInJavaEx2

Here, as you can see, that the output is not what was expected. Even though the strings s1 and s2 store the same values, it shows that they are not equal. This is so because this time, the equality operator is trying to compare objects and simply checks whether they refer to the same memory location or not. This is the reason it shows s4 and s1 as equal because they refer to the same memory location. Hence, for comparing strings, it’s always better to avoid the equality operator and choose other methods that are discussed below.

2. String Comparison Using the Strings.equals() Method

The Strings.equals() method in Java is used to compare the content or value stored in the strings. Irrespective of the fact whether the strings are created using double-quotes or as objects using a new operator, it will always compare with the content. Also, another point to note is that it is case-sensitive, so even if the two strings to be compared are different in terms of just the cases, they will be treated as unequal. To treat them as equal, you can use the Strings.equalsIgnoreCase() method that this article will discuss after this method. Let’s check out the example below.

Example 3

class StringCompare{

   public static void main(String args[]){

       String s1 = "Hello";

       String s2 = "Hello";

       String s3 = new String("Welcome");

       String s4 = new String("Welcome");

       String s5 = new String("Hello");

       if(s1.equals(s2)){

           System.out.println("Strings s1 and s2 are equal");

       }else{

           System.out.println("Strings s1 and s2 are not equal");

       }

       if(s1.equals(s5)){

           System.out.println("Strings s1 and s5 are equal");

       }else{

           System.out.println("Strings s1 and s5 are not equal");

       }

       if(s3.equals(s4)){

           System.out.println("Strings s3 and s4 are equal");

       }else{

           System.out.println("Strings s3 and s4 are not equal");

       }

       if(s4.equals(s5)){

           System.out.println("Strings s4 and s5 are equal");

       }else{

           System.out.println("Strings s4 and s5 are not equal");

       }

   }

}

Here, you have defined 5 strings, two of them directly using the double-quotes and 3 as objects using the new operator. Here, you must try to compare all the combinations. You have compared strings that are equal and both defined using double-quotes. Moving on, you have also compared strings that are equal and one of them is a double-quoted variable while the other one is an object defined using the new operator. Finally, it also tried to compare two string objects with the same values and different values. Let’s see the result.

StringComparisonInJavaEx3.

From the above output, it’s quite clear that the Strings.equals() method treats both objects and data-types the same way and only checks for the value stored inside rather than treating objects differently, like the equality operator.

3. String Comparison using the String.equalsIgnoreCase() Method

As discussed, the String.equals() method treats strings with the only difference in cases being unequal. Let’s check out an example for that as well.

Example 4

class StringCompare{

   public static void main(String args[]){

       String s1 = "Hello";

       String s2 = "hello";

       if(s1.equals(s2)){

           System.out.println("Strings s1 and s2 are equal");

       }else{

           System.out.println("Strings s1 and s2 are not equal");

       }

   }

}

Here, you have defined two strings called s1 and s2, and the only difference between the values stored inside them is that one string starts with a lowercase “h” and the other one starts with an uppercase “H”. Let’s see the output.

StringComparisonInJavaEx4

You can see that the method treats them as unequal. To override this behavior, you can use another method called Strings.equalsIgnoreCase() which is case-insensitive and treats strings with only case-differences as equals. Let’s verify the same with another example.

Example 5

class StringCompare{

   public static void main(String args[]){

       String s1 = "Hello";

       String s2 = "hello";

       String s3 = new String("heLLo");

       if(s1.equalsIgnoreCase(s2)){

           System.out.println("Strings s1 and s2 are equal");

       }else{

           System.out.println("Strings s1 and s2 are not equal");

       }

       if(s1.equalsIgnoreCase(s3)){

           System.out.println("Strings s1 and s3 are equal");

       }else{

           System.out.println("Strings s1 and s3 are not equal");

       }

   }

}

Here, you have defined 3 strings with only differences in their cases. Let’s see the output of the above program.

StringComparisonInJavaEx5

You can see that irrespective of whether it defines the strings directly using double-quotes or as objects with a new operator and whether they differ only regarding cases, the String.equalsIgnoreCase() methods treat them as equal.

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

4. String Comparison using the String.compareTo() Method

Till now, you have seen how to use the String.equals() method, String.equalsIgnoreCase() method, and the equality operator to compare strings and their default behaviors as well. Moving on, it’s time to see another method to achieve the same result called String.compareTo(). This method compares the strings differently. It compares the strings lexicographically and checks whether each character of the first string is equal to the second string or not. It can throw 3 types of output - 

  • If String 1 is equal to String 2, it will throw 0
  • If String 1 is less than String 2 (lexicographically smaller), it will throw a negative number
  • If String 1 is greater than String 2 (lexicographically greater), it will throw a positive number

Also, similar to the String.equals() method, this method also treats strings values that differ by cases as unequal. Let’s check out an example using this method.

Example 6

class StringCompare{

   public static void main(String args[]){

       String s1 = "Hello";

       String s2 = "Hello";

       String s3 = new String("Welcome");

       String s4 = new String("hello");

       System.out.println(s1.compareTo(s2));

       System.out.println(s1.compareTo(s3));

       System.out.println(s1.compareTo(s4));

   }

}

In the above example, you have defined 4 different strings, two as data-types and two as objects. Next, you must try to check how this method treats string variables or objects whose values differ by the case or by the value itself. Let’s check the output.

StringComparisonInJavaEx6

You can see that the outputs are integers. Now, try to break it down. First, you have compared s1 with s2, which has the same values with the same case. That’s why it has returned 0. In the next line, you have compared s1 with s3, which contains entirely different values. Also, the string s1 is lexicographically smaller than s2 because the word “Hello” comes before the letter “Welcome” in the dictionary. Hence, it has returned a random negative integer denoting that the string s1 is smaller than s2. In the last line, you have compared s1 with s4 whose content differs just by the starting letter’s case. It has returned a negative integer because it treats the lowercase letter “h” as smaller than the uppercase letter “H”.

5. String Comparison using the String.compareToIgnoreCase() Method

The method called String.compareTo() discussed above treats string variables with value differing by cases as unequal. To override this behavior, you can use the String.compareToIgnoreCase() method, which is case-insensitive. Let’s check it out with another simple example. The output pattern remains the same.

  • If s1 is equal to s2, then it returns 0
  • If s1 < s2, then it returns a negative integer
  • If s1 > s2, then it returns a positive integer

Example 7

class StringCompare{

   public static void main(String args[]){

       String s1 = "hello";

       String s2 = "hello";

       String s3 = new String("Welcome");

       String s4 = new String("Hello");

       System.out.println(s1.compareToIgnoreCase(s2));

       System.out.println(s1.compareToIgnoreCase(s3));

       System.out.println(s1.compareToIgnoreCase(s4));

   }

}

Here, instead of the String.compareTo(), you must use the String.compareToIgnoreCase() method which ignores the cases. Let’s check out the result of the execution.

StringComparisonInJavaEx7

Here, you can see that the strings s1 and s2 when compared, return 0 because they are the same. However, when you compared s1 which stores “hello” and s2 which stores “Hello”, it still returns 0, which means it treats them as equals. Thus, you can say that this method is case-insensitive.

6. String Comparison Using the Objects.equals() Method

You can also use the Objects.equals() method in Java to compare two strings either initialized with a new keyword or directly using double-quotes. This method checks whether both the strings objects are equal and if so, return true. It will also return true if both the strings are null. Let’s see how to use this method.

Example 8

import java.util.Objects;

class StringCompare{

   public static void main(String args[]){

       String s1 = "hello";

       String s2 = "hello";

       String s3 = new String("Hello");

       String s4 = new String("hello");

       String s5 = "Welcome";

       System.out.println("Is s1 and s2 equal? " + Objects.equals(s1, s2));

       System.out.println("Is s1 and s3 equal? " + Objects.equals(s1, s3));

       System.out.println("Is s1 and s4 equal? " + Objects.equals(s1, s4));

       System.out.println("Is s1 and s5 equal? " + Objects.equals(s1, s5));

   }

}

In the above example, you have used the Objects.equals() method to compare strings defined using double-quotes, using a new operator, and differing either completely or only with cases. Let’s check out the output.

StringComparisonInJavaEx8

You can see that the method returns the expected output and also treats strings values with different cases as unequal.

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion

In this guide, you looked into the different methods that can be used to compare strings in Java. You saw the six different ways, and how each one serves its one purpose. However, the methods Objects.equals() and String.equals() works as an all-rounder and you can always use them to get the best out of your Java program.

If you are looking to further your career as an expert Java developer, Simplilearn’s Full Stack Java Developer Master’s program is an ideal way to get a head start. Designed and delivered via the highly effective bootcamp model and in partnership with HIRIST and HackerEarth, this program offers you job-ready training in 30+ in-demand tools and skills, and let’s perfect them while learning with 20+ lesson-end, 6 phase-end, and 4 industry-aligned capstone project that you can use to showcase your Java expertise and job readiness to current or prospective employers.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, at the earliest!

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.