Proper Use Of String And StringBuffer In Java
Join the DZone community and get the full member experience.Join For Free
// 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); // DON'T DO THIS: // 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()