Core Java

Comparing Strings In Java

Introduction:

Strings are used all over in any Java application. So, it’s important to understand how to compare two string objects.

In this article, we’ll learn ways to compare String objects.

 

1.) Comparing References Using ‘==’

The == operator when used to compare strings is responsible for comparing only the references(not the content). So it will output true if two String references refer to the same object, false otherwise.

In the above example, although both str1 and str2 have the same content i.e. “ProgrammerGirl” but they are referring to two different objects, so str1 == str2 outputs false.

However, both str1 and str3 are referring to the same object stored in String Pool, so str1 == str3 outputs true.

2.) equals() method

String class in Java provides an equals() method which can be used to compare the string contents:

equals() method compares the value of String objects. Also, the comparison is case-sensitive. So if the two strings have exactly the same content equals() method outputs true, false otherwise.

3.) equalsIgnoreCase() method

The equalsIgnoreCase() method in Java help us achieve a non case-sensitive string content comparison.

It simply ignores the character-casing while comparing the string object contents.

4.) compareTo() method

The compareTo() method in String compares the two string contents lexicographically and returns an integer value as an output. The method str1.compareTo(str2) would return:

  • A positive value, if str1 is lexicographically greater than str2
  • 0, if str1 is equal to str2
  • A negative value, if str1 is lexicographically less than str2

5.) compareToIgnoreCase() method

This method is exactly the same as compareTo(), except the fact that it ignores the character casing.

Conclusion:

In this quick tutorial, we explored ways in which we can compare String objects in Java.

 

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *