Java – String contentEquals(StringBuffer sb) method

In this article, we will discuss String comparison with StringBuffer using String’s contentEquals() method

1. String’s contentEquals(StringBuffer sb) method:

  • This String method compares the contents of string with supplied/passed StringBuffer

1.1 Method Signature:

public boolean contentEquals(StringBuffer sb);

1.2 Returns:

Returns a boolean value either true or false

  • True –> if string matches with StringBuffer
  • False –> if string doesn’t matches with StringBuffer

2. Examples on contentEquals() method:

  • Below demo program compares String with StringBuffer using String’s contentsEquals() method

StringContentEqualsMethod.java

package in.bench.resources.string.methods;

public class StringContentEqualsMethod {

	public static void main(String[] args) {

		// String literals
		String str1 = "BenchResources.Net";
		String str2 = "Oracle.Com";

		// StringBuffer
		StringBuffer sb1 = new StringBuffer("BenchResources.Net");

		// comparing String and StringBuffer
		boolean contentEquals1 = str1.contentEquals(sb1);

		// printing to console
		System.out.println("str1 contentsEqual with sb1 : "
				+ contentEquals1);

		// again, comparing String and StringBuffer
		boolean contentEquals2 = str2.contentEquals(sb1);

		// printing to console
		System.out.println("str2 contentsEqual with sb1 : "
				+ contentEquals2);
	}
}

Output:

str1 contentsEqual with sb1 : true
str2 contentsEqual with sb1 : false

Note: There is one variation to this String method which accepts CharSequence as input arguments

Method Signature:

public boolean contentEquals(CharSequence cs);

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - String copyValueOf(char[] data) method
Java - String contains(CharSequence s) method with example