Java – Compare Content of a String and StringBuffer
To compare content of a String str and StringBuffer stringBuffer in Java, use String.contentEquals() method. Call contentEquals() method on the string str and pass the StringBuffer object stringBuffer as argument. If the content of str equals the content of , then contentEquals() method returns true.stringBuffer
Java Program
</>
Copy
public class Example {
public static void main(String[] args) {
String str = "apple";
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append('a');
stringBuffer.append('p');
stringBuffer.append('p');
stringBuffer.append('l');
stringBuffer.append('e');
boolean result = str.contentEquals(stringBuffer);
System.out.println("Does str and stringBuffer have same content? " + result);
}
}
Output
Does str and stringBuffer have same content? true
If the string str and StringBuffer object stringBuffer 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";
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append('a');
stringBuffer.append('p');
boolean result = str.contentEquals(stringBuffer);
System.out.println("Does str and stringBuffer have same content? " + result);
}
}
Output
Does str and stringBuffer have same content? false
Conclusion
In this Java Tutorial, we learned how to compare the content of a String and StringBuffer in Java.
