Comparing Strings in Java: equals() Vs contentEquals()

06 May 2023 Balmiki Mandal 0 Core Java

String equals() Vs contentEquals() in Java

The equals() and contentEquals() methods of the String class are used to check if two string objects contain the same characters. Both methods take in a single argument, which could be another String object, a StringBuffer or a CharSequence. However, there is an important difference between these two methods that should be noted.

The equals() method checks whether two string objects are equal; it returns true if both strings have the same sequence of characters. On the other hand, the contentEquals() method checks for content equality, which means that it will return true even if the argument is not a String but contains the same characters as the original string. For example, if you call contentEquals() on a String object with a StringBuffer argument that has the same characters as the string object, the result will be true.

To summarise, the equals() method compares two strings character by character whereas the contentEquals() method can compare strings with any other CharSequence. It is important to note that none of these methods is case sensitive and they don’t perform any whitespace trimming.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.