A simple rule of thumb (String is a type that represents character strings. StringBuilder a stream of mutable characters)
Use String
to represent text values. By definition Java provides pooling of string values and thus providing you some space optimization. Think of this in a scenario where your application is dealing with millions of text values during a file batch processing. So as an example.
String str1 = "Test";
String str2 = "Test";
Here, str1 == str2 ( same reference)
Also, +
operator is overloaded in String to construct String from different types. This can be used when constructing small Strings ( internally it gets done using StringBuilder
so no worries) - but not while looping.
Use StringBuilder
(or old counterpart StringBuffer
) only when you are constructing a target String using small pieces of different types - and especially inside a loop - this will help you to avoid placing unnecessary string fragments in the string pool.
StringBuilder s1 = new StringBuilder("test");
StringBuilder s2 = new StringBuilder("test");
Here, s1 != s2
Also, I do not think there is someway you can manipulate the encoding of StringBuilder/Buffer - Meanwhile String allows this.
Edit: Representing Hibernate entities :
Always use String
to represent a text type in your class. For reasons stated above.This should come to you like muscle memory. For example, int
, float
, char
etc for primitive types and String
for text type. Use the builder only to build strings and not to represent a type unless that is some strange requirement.