0

I have appended some strBuild with some characters and putting that strBuild into stringBuildArr. then called the java.lang.StringBuilder.delete(int start, int end) function on strBuild.

Here is the issue not only this deletes the data from strBuild but also from stringBuildArr.

    StringBuilder strBuild = new StringBuilder();
    StringBuilder stringBuildArr[] = new StringBuilder[10];
    strBuild.append("hgfd");
    stringBuildArr[0] = strBuild;
    System.out.println("Output1: "+stringBuildArr[0]);
    strBuild.delete(0, strBuild.length());
    System.out.println("Output2: "+stringBuildArr[0]);

RESULT

Output1: hgfd

Output2:

so, how does storage of these stringbuilder and stringbuffer class works?

2 Answers 2

1

There is no "issue" here, the array stores a reference to the same strBuild instance; there is no copy with stringBuildArr[0] = strBuild; because copying the StringBuilder is not free. But if you want a copy that is easy enough, change it to

stringBuildArr[0] = new StringBuilder(strBuild);
Sign up to request clarification or add additional context in comments.

3 Comments

i named it an issue for lack of better word. what does this "because copying the StringBuilder is not free" mean?
@elliot, seems like he was not sure how to ask or how to mention, he is new.
@vaibhavcool20 It means creating a unique reference copy of the StringBuilder instance requires a copy operation which is not required in all cases. In short, TANSTAAFL
1

The Java StringBuilder is a class that most Java programmers are familiar with. Strings are immutable, so every change in a string will cause a new object created however in StringBuilder or buffer, it is mutable. This means it will work on the same object, so deleting will delete the content and hence all reference pointing to the same object will have the same behaviour.

For more info check out the official documentation: Java Docs

2 Comments

so, when i call this ` stringBuildArr[0] = strBuild;` only reference is shared not its content?.
@vaibhavcool20 , Yea logically you can say that. It's better to go through with the official link I shared, it will remove all your doubts. String concept is very wide and in Java world one should be very clear to that. Happy coding, accept the answer if you are clear, it will help others

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.