Java String - contentEquals() Method
The Java contentEquals() method is used to compare the given string to the specified CharSequence or StringBuffer. It returns true if the string represents the same sequence of char values as the specified sequence or the same sequence of characters as the specified StringBuffer, else returns false.
Syntax
public boolean contentEquals(CharSequence cs) public boolean contentEquals(StringBuffer sb)
Parameters
cs |
specify the sequence to compare against the given string. |
sb |
specify the StringBuffer to compare against the given string. |
Return Value
Returns true if the string represents the same sequence of char values as the specified sequence or the same sequence of characters as the specified StringBuffer, else returns false.
Exception
NA.
Example:
In the example below, contentEquals() method is used to check whether the given string str1 represents the same sequence of char values as the strings str2 and str3.
public class MyClass { public static void main(String[] args) { String str1 = "Hello World"; String str2 = "Hello World"; String str3 = "Hello"; System.out.println(str1.contentEquals(str2)); System.out.println(str1.contentEquals(str3)); } }
The output of the above code will be:
true false
Example:
In the example below, contentEquals() method is used to check whether the given string str1 represents the same sequence of char values as the sequences str2 and str3.
public class MyClass { public static void main(String[] args) { String str1 = "Java"; CharSequence str2 = "Java"; CharSequence str3 = "Python"; System.out.println(str1.contentEquals(str2)); System.out.println(str1.contentEquals(str3)); } }
The output of the above code will be:
true false
Example:
In the example below, the given string str1 is compared with StringBuffers str2 and str3.
public class MyClass { public static void main(String[] args) { String str1 = "Hello World"; StringBuffer str2 = new StringBuffer("Hello World"); StringBuffer str3 = new StringBuffer("World"); System.out.println(str1.contentEquals(str2)); System.out.println(str1.contentEquals(str3)); } }
The output of the above code will be:
true false
❮ Java String Methods