Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
string
charsequence
stringbuffer
communitycreator

What is the String.contentEquals method in Java?

Programming Bytes

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

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.

RELATED TAGS

java
string
charsequence
stringbuffer
communitycreator

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

Keep Exploring
Related Courses