Java – Compare Content of a String and CharSequence

To compare content a String str and CharSequence charSequence in Java, use String.contentEquals() method. Call contentEquals() method on the string str and pass the CharSequence object charSequence as argument. If the content of str equals the content of charSequence, then contentEquals() method returns true.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args) {
		String str = "apple";
		CharSequence charSequence = "apple";
		boolean result = str.contentEquals(charSequence);
		System.out.println("Does str and charSequece have same content? " + result);
	}
}

Output

Does str and charSequece have same content? true

If the string str and CharSequence object charSequence does not have same content, then contentEquals() method returns false.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args) {
		String str = "apple";
		CharSequence charSequence = "mango";
		boolean result = str.contentEquals(charSequence);
		System.out.println("Does str and charSequece have same content? " + result);
	}
}

Output

Does str and charSequece have same content? false

Conclusion

In this Java Tutorial, we learned how to compare a String and CharSequence in Java.