What is the String.contentEquals method in Java?

The contentEquals method is used to check if the content of the string is equal to the passed CharSequenceA CharSequence is a readable sequence of char values. or StringBufferA string buffer is like a mutable String..

Syntax

string.contentEquals(StringBuffer sb)
string.contentEquals(CharSequence cs)

Parameters

  • The contentEquals method expects a StringBuffer or CharSequence as an arguemnt.

  • Any class that implements the CharSequence class can also be passed as an argument to the contentEquals method. Examples include CharBuffer, Segment, String, StringBuffer, and StringBuilder.

Return value

The contentEquals method returns true if the content of the string and the passed StringBuffer/CharSequence are equal. Otherwise, it returns false.

Code

class ContentEquals {
public static void main( String args[] ) {
String str = "Java";
StringBuffer sb= new StringBuffer("Java");
StringBuffer sb2= new StringBuffer("JavaScript");
System.out.println( "str = " + str);
System.out.println( "sb = " + sb);
System.out.println( "sb = " + sb2);
System.out.print( "\nCallingn str.contentEquals(sb) ");
System.out.println(str.contentEquals(sb));
System.out.print( "\nCallingn str.contentEquals(sb2) ");
System.out.println(str.contentEquals(sb2));
}
}

Explanation

In the code above, we have:

  • Created a:

    • str string with the value Java.
    • sb* StringBuffer with the value Java .
    • Another sb2 StringBuffer with the value JavaScript.
  • Called the contentEquals method on the str object by passing sb as an argument.

  • The contentEquals method will compare the string str to the specified StringBuffer sb. The return value is true if and only if str represents the same sequence of characters as the specified StringBuffer sb. In our case, both the string and StringBuffer have the same sequence of characters, so we get true as a return value.

  • Called the contentEquals method on the str object by passing the sb2 as an argument. In this case, str's value Java is not equal to sb2's value JavaScript, so false is returned.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources