StringBuilder a = new StringBuilder("abc");
StringBuilder b = a.append("de");
b = b.append("f").append("g");
System.out.println("a=" + a);
System.out.println("b=" + b);
Why is the output of both a &b is the same?
Let me break up the line StringBuilder b = a.append("de");
Here a.append("de") means
a = a + "de". ie a = "abcde"
then StringBuilder b = a.append("de") = a;
Now StringBuilder b and a have same reference.
To avoid this issue you have to create a new StringBuilder object for b.
I think this is what you are looking for:
StringBuilder a = new StringBuilder("abc");
StringBuilder b = new StringBuilder(a.append("de"));
b = b.append("f").append("g");
System.out.println("a=" + a);
System.out.println("b=" + b);
The output will now be:
a=abcde
b=abcdefg
In your case 'b' is also just a reference to 'a'. Which means 'a' and 'b' are referencing to same object. Any change in one will reflect onto the other.
In line 2, when you say "StringBuilder b = a.append("de")" you're essentially linking both of them together. So, the 2 of them are the same at that point. When you do a.append("de"), that line has 2 functions. One is to add "de" to the StringBuilder a. The second is to set StringBuilder b to String builder a. So, since both of them are set to the same thing, the result comes out the same.
StringBuilder is not immutable. It only returns an instance of itself as a convenience so you can chain methods. So a and b refer to the same instance as shown here.
StringBuilder a = new StringBuilder("abc");
StringBuilder b = a.append("de");
b = b.append("f").append("g");
System.out.println("a=" + a);
System.out.println("b=" + b);
System.out.println("a = " + System.identityHashCode(a));
System.out.println("b = " + System.identityHashCode(b));
System.out.println(a == b);
Prints
a=abcdefg
b=abcdefg
a = 925858445
b = 925858445
true
StringBuilder b = a.append("de");I think you copy the reference in memory to b. Then the appending will applied to both because both referencing the same object in memory.