w3resource logo


Introduction to Java Programming

Java String: contentEquals() Method

Secondary Nav

contentEquals() Method

Contents:

public boolean contentEquals(CharSequence cs)

This method compares the string to the specified CharSequence. The result is true if and only if this String represents the same sequence of char values as the specified sequence.

Note: If the CharSequence is a StringBuffer then the method synchronizes on it

Java Platform: Java SE 8

Syntax :

contentEquals(CharSequence cs)

Parameters:

Name Description boolean
cs The sequence to compare this String against. string

Return Value : true if this String represents the same sequence of char values as the specified sequence, false otherwise.

Return Value Type: boolean

Example : Java String contentEquals() Method

The following example shows the usage of java String() method.

public class Example {
public static void main(String[] args) {
    String str1 = "example.com", str2 = "Example.com";
    CharSequence cs = "example.com";
System.out.println();
System.out.println("Comparing "+str1+" and "+cs+": " + str1.contentEquals(cs));
System.out.println("Comparing "+str2+" and "+cs+": " + str2.contentEquals(cs));
System.out.println();
    }
}

Output:

Comparing example.com and example.com: true            
Comparing Example.com and example.com: false

public boolean contentEquals(StringBuffer sb)

This method compares a specified string to the specified StringBuffer. The result is true if and only if this String represents the same sequence of characters as the specified StringBuffer. This method synchronizes on the StringBuffer.

Java Platform: Java SE 8

Syntax :

contentEquals(StringBuffer sb)

Parameters:

Name Description boolean
sb The StringBuffer to compare this String against.

Return Value : true if this String represents the same sequence of characters as the specified StringBuffer, false otherwise.

Return Value Type: boolean

Example : Java String contentEquals() Method

The following example shows the usage of java String() method.

public class Example {

public static void main(String[] args) {

    String str1 = "example.com", str2 = "Example.com";
StringBuffer strbuf = new StringBuffer(str1);
System.out.println();
System.out.println("Comparing "+str1+" and "+strbuf+": " + str1.contentEquals(strbuf));

System.out.println("Comparing "+str2+" and "+strbuf+": " + str2.contentEquals(strbuf));
System.out.println();

      }
}

Output:

Comparing example.com and example.com: true            
Comparing Example.com and example.com: false

Java Code Editor:



Join our Question Answer community to learn and share your programming knowledge.