String operations make Java slower, because String is immutable. StringBuffer is more efficient. Anyone who has either prepared or taken Java Certification or Interviews would have come across this question. But really, while programming how does one decide between these classes, why are they even provided by the language?
While running the code against JTest, I came across a line which looked like:
void func(String var2) {
String var1 = new String(var2) ;
}
new String(String) ? What is the intent of this line. How is it different from:
String var1 = var2;
Why is Java providing such a constructor if it doesn’t make sense? Apparently it does make sense in one case, during creation of substrings. Check this article at Java Glossary by Roedy Green. He explains, that if one doesn’t use new String(String), there might be a potential memory leak. Also his article on String class itself is very informative. (He has updated with the notes on StringBuilder introduced recently into Java.)
Jon has details in his article -Strings/StringBuffers, the memory usage and shows how it impacts the performance. The article from JavaWorld by Reggie Hutcherson walks through the byte code operations involved when using Strings and StringBuffers.
For brief guidelines on when to use String and StringBuffer, check the DZone Article.
Now if you are still wondering why Strings were made immutable in the first place. Check this article – why is String immutable and final? Strings(and all the wrapper classes like Integer) are special classes, they are treated like primitive data-types. (Unlike the usual usual Java object philosophy where objects are references and passed by values in the function calls.)
The story doesn’t end there, there is a hack to make the string mutable by using the reflection API. But why would anyone do it?