English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I)/O)

Java Reader/Writer

Other Java Topics

Java String contentEquals() Usage and Example

Java String (String) Methods

The Java String contentEquals() method checks whether the content of String is equal to the specified charSequence / StringBuffer

The syntax of the string contentEquals() method is:

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

Here, string is an object of the String class.

Parameters of contentEquals()

  • Accepts StringBuffer or charSequence

Note:You can pass any class that implements CharSequence to the contentEquals() method. For example: String, StringBuffer, CharBuffer, etc.

Return value of contentEquals()

  • If the string contains the character sequence specified by the parameter, it returns true. Otherwise, it returns false.

Example: Example of using the Java string contentEquals() method

class Main {
  public static void main(String[] args) {
    String str = "Java";
    String str1 = "Java";
    StringBuffer sb1 = new StringBuffer("Java");
    CharSequence cs1 = "Java";
    String str2 = "JavA";
    StringBuffer sb2 = new StringBuffer("JavA");
    CharSequence cs2 = "JavA";
    System.out.println(str.contentEquals(str1)); // true
    System.out.println(str.contentEquals(sb)1)); // true
    System.out.println(str.contentEquals(cs)1)); // true
    System.out.println(str.contentEquals(str2)); // false
    System.out.println(str.contentEquals(sb)2)); // false
    System.out.println(str.contentEquals(cs)2)); // false
  }
}

Java String equals() vs contentEquals()

The Java String equals() method not only compares the content but also checks if the other object is an instance of String. However, contentEquals() only compares the content. For example,

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    StringBuffer sb1 = new StringBuffer("Java");
    System.out.println(str1).equals(sb1)); // false
    System.out.println(str1).contentEquals(sb1)); // true
  }
}

Here, str1and sb1Both have the same content, but they are instances of different objects. Therefore, str1).equals(sb1) returns false and str1).contentEquals(sb1) returns true.

Java String (String) Methods