String comparison in Java

  • Last Updated: January 14, 2025
  • By: javahandson
  • Series
img

String comparison in Java

Learn everything about string comparison in Java using methods like equals(), equalsIgnoreCase(), ==, compareTo(), and compareToIgnoreCase(). Understand their differences and how to use them effectively for precise string handling.

 

String comparison in Java is achieved through a variety of methods, including equals(), equalsIgnoreCase(), ==, compareTo(), and compareToIgnoreCase(). Each method serves a specific purpose, allowing developers to compare strings based on content, case sensitivity, reference equality, or lexicographical order.

#equals method

The equals method compares the content of two strings for equality. If the contents are exactly the same then the method returns true or will return false.

package com.javahandson.string;

public class StringComparison {
    public static void main(String[] args) {

        String str1 = "JavaHandsOn";
        String str2 = "JavaHandsOn";
        String str3 = new String("JavaHandsOn");

        System.out.println("Compare str1 and str2 : " + str1.equals(str2)); // true
        System.out.println("Compare str1 and str3 : " + str1.equals(str3)); // true
        System.out.println("Compare str2 and str3 : " + str2.equals(str3)); // true		
    }
}
Output:
Compare str1 and str2 : true
Compare str1 and str3 : true
Compare str2 and str3 : true

str1 and str2 point to the same memory location in the string constant pool area whereas str3 is in the heap area. But as the content is the same for all the strings hence the equals method returns true in all the 3 cases.

#equals method considers the uppercase and lowercase as well. If the case did not match then it returns false.

package com.javahandson.string;

public class StringComparison {
    public static void main(String[] args) {

        String str1 = "JavaHandsOn";
        String str2 = "JAVAHandsOn";
        String str3 = new String("JavaHandsOn");

        System.out.println("Compare str1 and str2 : " + str1.equals(str2)); // false
        System.out.println("Compare str1 and str3 : " + str1.equals(str3)); // true
        System.out.println("Compare str2 and str3 : " + str2.equals(str3)); // false		
    }
}
Output:
Compare str1 and str2 : false
Compare str1 and str3 : true
Compare str2 and str3 : false

In the above example content of the strings are same but the str2 case is different from str1 and str3 hence if str2 is compared with either str1 or str3 then it returns false.

#equalsIgnoreCase method

The #equalsIgnoreCase method compares the content of two strings for equality, ignoring the case or we can say this method is case-insensitive.

package com.javahandson.string;

public class StringComparison {
    public static void main(String[] args) {

        String str1 = "JavaHandsOn";
        String str2 = "JAVAHandsOn";
        String str3 = new String("JavaHandsOn");

        System.out.println("Compare str1 and str2 : " + str1.equalsIgnoreCase(str2)); // true
        System.out.println("Compare str1 and str3 : " + str1.equalsIgnoreCase(str3)); // true
        System.out.println("Compare str2 and str3 : " + str2.equalsIgnoreCase(str3)); // true
    }
}
Output:
Compare str1 and str2 : true
Compare str1 and str3 : true
Compare str2 and str3 : true

In the above example str2 case is different from str1 and str3 but as we are using the #equalsIgnoreCase method hence it ignores the case comparison and it returns true in all three cases.

== operator

The == operator compares the references of two strings i.e. it checks whether the two strings point to the same memory location or not. If the references point to the same memory location then it returns true else it returns false. The == operator does not compare the content of the strings.

package com.javahandson.string;

public class StringComparison {
    public static void main(String[] args) {

        String str1 = "JavaHandsOn";
        String str2 = "JavaHandsOn";
        String str3 = new String("JavaHandsOn");

        System.out.println("Compare str1 and str2 : " + (str1 == str2)); // true
        System.out.println("Compare str1 and str3 : " + (str1 == str3)); // false
        System.out.println("Compare str2 and str3 : " + (str2 == str3)); // false		
    }
}
Output:
Compare str1 and str2 : true
Compare str1 and str3 : false
Compare str2 and str3 : false

str1 and str2 point to the same memory location in the string constant pool area hence the == operator returns true whereas str3 points to a different location in the heap memory so str1 and str2 will not be equal to str3.

#compareTo method

The compareTo method compares the content of two strings lexicographically based on unicode value.

Note* The term lexicographically refers to the way words are ordered in a dictionary. In the context of strings, it means comparing them character by character based on their Unicode values. The comparison starts from the first character and continues until a difference is found or one of the strings ends.

  • Returns 0 if the strings are equal.
  • Returns a negative integer if the first string is lexicographically less than the second string.
  • Returns a positive integer if the first string is lexicographically greater than the second string.

Example of Unicode Comparison:

‘J’ has a Unicode value of 74.
‘H’ has a Unicode value of 72.
‘j’ has a Unicode value of 106.

This means:

“H” comes before “J” because 72 < 74.
“HandsOn” comes before “Java” because of ‘H’ < ‘J’.
“Java” comes before “java” because the lowercase ‘j’ has a larger Unicode value than the uppercase ‘J’.

package com.javahandson.string;

public class StringComparison {
    public static void main(String[] args) {

        String str1 = "Java";
        String str2 = "HandsOn";
        String str3 = new String("java");

        System.out.println("Compare str1 and str2 : " + (str1.compareTo(str2)));
        System.out.println("Compare str1 and str3 : " + (str1.compareTo(str3)));
        System.out.println("Compare str2 and str3 : " + (str2.compareTo(str3)));
    }
}
Output:
Compare str1 and str2 : 2
Compare str1 and str3 : -32
Compare str2 and str3 : -34

str1 = “Java” comes after str2 = “HandsOn” lexicographically and since “Java” is lexicographically greater than “HandsOn” hence it returns a positive number.

str1 = “Java” comes before str2 = “java” lexicographically and since “Java” is lexicographically less than “java” hence it returns a negative number.

str1 = “HandsOn” comes before str2 = “java” lexicographically and since “HandsOn” is lexicographically less than “java” hence it returns a negative number.

#compareToIgnoreCase method

The #compareToIgnoreCase method compares the content of two strings lexicographically based on unicode value, ignoring the case or case-insensitive. It is the same as the #compareTo method just it doesn’t consider letter case when comparing.

package com.javahandson.string;

public class StringComparison {
    public static void main(String[] args) {

        String str1 = "Java";
        String str2 = "HandsOn";
        String str3 = new String("java");

        System.out.println("Compare str1 and str2 : " + (str1.compareToIgnoreCase(str2)));
        System.out.println("Compare str1 and str3 : " + (str1.compareToIgnoreCase(str3)));
        System.out.println("Compare str2 and str3 : " + (str2.compareToIgnoreCase(str3)));
    }
}
Output:
Compare str1 and str2 : 2
Compare str1 and str3 : 0
Compare str2 and str3 : -2

str1 = “Java” comes after str2 = “HandsOn” lexicographically and since “Java” is lexicographically greater than “HandsOn” hence it returns a positive number.

str1 = “Java” comes before str2 = “java” lexicographically but #compareToIgnoreCase does not consider the case hence ‘J’ will be equal to ‘j’ and the rest of the letters are the same so str1 is equal to str3 and the method returns 0.

str1 = “HandsOn” comes before str2 = “java” lexicographically and since “HandsOn” is lexicographically less than “java” hence it returns a negative number.

Conclusion

String comparison is a fundamental concept in Java that provides various methods to suit different use cases. Understanding the difference between the == and #equals methods is crucial as the former compares references while the latter compares content. For sorting or ordering strings methods like #compareTo and #compareToIgnoreCase offer lexicographical comparisons based on Unicode values.

So this is all about the string comparison in Java. If you have any questions on this topic, please raise them in the comments section. If you liked this article then please share this post with your friends and colleagues.

Leave a Comment