Immutable String and when to use StringBuffer/StringBuilder versus String

I was taught that Java Strings are immutable. What this means to me is that if we do the following:

String product="radio";

in your program memory you have someone still stored "radio" but you can't see it. But its sitting there wasting memory (until garbage cleanup). If you are detailing with same a million products it might be of concern. Below is my code solution where I use StringBuilder because I believe StringBuilder is cleaned up on the fly.

Question when should I use String versus StringBuffer or Builder (I understand that buffer is threadsafe but slightly less efficient than builder).  And does StringBuffer still have same memory problem as String?
Iterator it = productMap.keySet().iterator();
//Need to use key below, but since key may change over a million times
//use StringBuilder versus just a String?
while (it.hasNext()) {
   StringBuilder key = new StringBuilder(;
   productBean = (ProductBean)productMap.get(key.toString());
   if (productBean.getPriority().equals("1")) {
   } // end of checking for product still in use
//or should I just use the following:
while (it.hasNext()) {
   String key = new StringBuilder(;
   productBean = (ProductBean)productMap.get(key);
   if (productBean.getPriority().equals("1")) {
   } // end of checking for product still in use

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Essentially you have answered your own question, since Strings are immutable setting a string to a million different values could cause quite a performance hit.

So, when you need to iterate with a string (or append) use StringBuilder, unless you require it to be thread safe, then use StringBuffer.
CPColinSenior Java ArchitectCommented:
Each of those calls to the toString method is creating a String object, so you're not really gaining anything by doing this. Also, if productMap has String objects as its keys, you've got even less chance of this code structure making any difference, since all those String instances are already being stored in the map.

It is true, though, that String LITERALS can take up memory; they're stored in the pool of constants that gets loaded (and unloaded) along with whatever class uses them.

Ultimately, though, you shouldn't worry about it. Go ahead and try it both ways if you want; there's probably not going to be much difference.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
You are talking about 2 things here:
1. String is Immutable. This means that once you have created a instance of
   String class, you can't change it. Any change will lead to creation of
   string class. If you look at documentation there is no set method.
   Now, StringBuffer or StringBuilder is not Immutable, so, once you create
   instance of Stringbuffer, you can modify the elements of it.
   java.awt.Color is another example of Immutable class.
2. caching of string constants:
   String product = "radio";
   Here the value radio is cached. Like any other caching it has certain
   and timeout after which it will be collected.
maxmohaveAuthor Commented:
All three answers were good, but I guess what I was really looking for was a best practice answer. The answer that I chosed as correct indicated that either way I approached my problem I was going to be creating strings over and over. Main thing is the toString method creates a string anyway, so I don't gain anything.
Thanks everyone.
maxmohaveAuthor Commented:

sorry about the B grade. CPColin answered perfectly, I wish I could go back and change grade. I was clicking through too fast.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.