Over a million developers have joined DZone.

Proper Use Of String And StringBuffer In Java

DZone's Guide to

Proper Use Of String And StringBuffer In Java

Free Resource
// This isn't really code at all, this is a comment that I use 
// over and over again as I go through code written by people 
// who obviously don't understand when to use a String and when
// to use a StringBuffer.

// I put this block of text wherever I find problems with Strings
// and StringBuffers to improve understanding of how each one works
// and when to use one or the other.
// Rule #1: Use a StringBuffer if you intend to build a string out of
// dynamic elements. That is, if you are going to include the results
// of function calls or variables as part of the string then you use
// a StringBuffer and do append() calls. StringBuffer's append is
// much faster than using "+" to stick together String objects.
// Rule #2: But, if you are just building a string out of static pieces
// of text, it's better to use Strings and "+" than creating a
// StringBuffer and making append calls. Instead just use a String
// and a bunch of "+" signs between the sections. For example:
// String test = "this " + "is " + "a " + "test " + "string";
// is _not_ expensive. Why? Because all the pieces are static text and
// the compiler can make it into this _as it compiles the code_:
// String test = "this is a test string";
// Rule #3: For goodness sake, do this:
// StringBuffer test = new StringBuffer();
// test.append("static string ");
// test.append(dynamicCall());
// test.append(" another static string ");
// test.append(someVariable);
// StringBuffer test = new StringBuffer();
// test.append("static string " + dynamicCall());
// test.append(" another static string " + someVariable);
// This is officially the worst of all worlds. You need to use a
// StringBuffer in this case because you've got some dynamic parts
// but there is still addition going on between dynamic parts (the
// function call and variable) and static strings. Ack!
// If you can't remember anything else, remember this:
// static strings = String and "+"
// dynamic strings = StringBuffer and append() 

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}