Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 718725
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T05:33:37+00:00 2026-05-14T05:33:37+00:00

How can we re assign the value of a StringBuffer or StringBuilder Variable? StringBuffer

  • 0

How can we re assign the value of a StringBuffer or StringBuilder Variable?

StringBuffer sb=new StringBuffer("teststr");

Now i have to change the value of sb to “testString” without emptying the contents.
I am looking at a method which can do this assignment directly without using separate memory allocation.I think we can do it only after emptying the contents.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T05:33:37+00:00Added an answer on May 14, 2026 at 5:33 am

    It should first be mentioned that StringBuilder is generally preferred to StringBuffer. From StringBuffer‘s own API:

    As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

    That said, I will stick to StringBuffer for the rest of the answer because that’s what you’re asking; everything that StringBuffer does, StringBuilder also… except synchronization, which is generally unneeded. So unless you’re using the buffer in multiple threads, switching to StringBuilder is a simple task.


    The question

    StringBuffer sb = new StringBuffer("teststr");
    

    “Now i have to change the value of sb to "testString" without emptying the contents”

    So you want sb to have the String value "testString" in its buffer? There are many ways to do this, and I will list some of them to illustrate how to use the API.


    The optimal solution: it performs the minimum edit from "teststr" to "testString". It’s impossible to do it any faster than this.

    StringBuffer sb = new StringBuffer("teststr");
    sb.setCharAt(4, 'S');
    sb.append("ing");
    assert sb.toString().equals("testString");
    

    This needlessly overwrites "tr" with "tr".

    StringBuffer sb = new StringBuffer("teststr");
    sb.replace(4, sb.length(), "String");
    assert sb.toString().equals("testString");
    

    This involves shifts due to deleteCharAt and insert.

    StringBuffer sb = new StringBuffer("teststr");
    sb.deleteCharAt(4);
    sb.insert(4, 'S');
    sb.append("ing");
    assert sb.toString().equals("testString");
    

    This is a bit different now: it doesn’t magically know that it has "teststr" that it needs to edit to "testString"; it assumes only that the StringBuffer contains at least one occurrence of "str" somewhere, and that it needs to be replaced by "String".

    StringBuffer sb = new StringBuffer("strtest");
    int idx = sb.indexOf("str");
    sb.replace(idx, idx + 3, "String");
    assert sb.toString().equals("Stringtest");
    

    Let’s say now that you want to replace ALL occurrences of "str" and replace it with "String". A StringBuffer doesn’t have this functionality built-in. You can try to do it yourself in the most efficient way possible, either in-place (probably with a 2-pass algorithm) or using a second StringBuffer, etc.

    But instead I will use the replace(CharSequence, CharSequence) from String. This will be more than good enough in most cases, and is definitely a lot more clear and easier to maintain. It’s linear in the length of the input string, so it’s asymptotically optimal.

    String before = "str1str2str3";
    String after = before.replace("str", "String");
    assert after.equals("String1String2String3");
    

    Discussions

    “I am looking for the method to assign value later by using previous memory location”

    The exact memory location shouldn’t really be a concern for you; in fact, both StringBuilder and StringBuffer will reallocate its internal buffer to different memory locations whenever necessary. The only way to prevent that would be to ensureCapacity (or set it through the constructor) so that its internal buffer will always be big enough and it would never need to be reallocated.

    However, even if StringBuffer does reallocate its internal buffer once in a while, it should not be a problem in most cases. Most data structures that dynamically grows (ArrayList, HashMap, etc) do them in a way that preserves algorithmically optimal operations, taking advantage of cost amortization. I will not go through amortized analysis here, but unless you’re doing real-time systems etc, this shouldn’t be a problem for most applications.

    Obviously I’m not aware of the specifics of your need, but there is a fear of premature optimization since you seem to be worrying about things that most people have the luxury of never having to worry about.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 379k
  • Answers 379k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer if you add session_start() to the top of your page… May 14, 2026 at 9:25 pm
  • Editorial Team
    Editorial Team added an answer I have the same problem, my chosen themes are always… May 14, 2026 at 9:25 pm
  • Editorial Team
    Editorial Team added an answer The simplest solution if you have PC's and DB server… May 14, 2026 at 9:25 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.