Comparing String and StringBuffer contents
StringBuffer class's objects act like a buffer for adding string contents. As very popularly known that StringBuffer objects are mutable and modifying the contents of string buffer doesn't create new objects. But sometimes, one requires to compare the contents of String object with the contents of StringBuffer object.
package com.example;
/** This class is a Java tutorial for comparing string and stringbuffer contents in Java
*
* @author Extreme Java
*/
public class Test{
/** This method shows how to compare string and stringbuffer in Java
*
* @param args
*/
public static void main(String[] args) {
String str = "This is a String";
StringBuffer sb = new StringBuffer("This");
System.out.println(str.equals(sb.toString()));
sb = new StringBuffer("This is a String");
System.out.println(str.equals(sb.toString()));
}
}
output:
false
true
As seen in the above code and the corresponding output, the toString() method of StringBuffer class which returns the string representation of the string buffer object.
No comments:
Post a Comment