StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer(sb1);
sb1.append("d");
System.out.println(sb2);
Since StringBuffer is mutable and sb2 points to sb1, i would expect sb2 to have "abcd" as the value. Though the question is layman, could you please help me explain this.
StringBuffer creates a new object in Heap on calling new StringBuffer(sb1)
. It does not point to sb1
.
If you wish to make sb2
point to sb1
, then declare StringBuffer sb2 = sb1
public StringBuffer(String str)
Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16 plus the length of the string argument.