0
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?

1
  • 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. Commented Jan 8, 2021 at 13:36

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You. You have explained so well!
0

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.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.