Search code examples
javahibernatejpaormstringbuilder

In Java, when should I prefer String over StringBuilder vice versa?


I know StringBuilder should be preferred over String because String will be kept in Constant String Pool and assigning a new value to it does not override the previous values. However, StringBuilder is an object that overrides its previous value.

  • In what cases should I use String over StringBuilder vice versa.
  • Also If I have variables of type String in backing classes of Hibernate should I use StringBuilder? How?

    ...
    Result result = (Result) criteria.list().get(0);
    
    
    class Result{
       String name;
       String fname;
       ...
    }
    

Solution

  • You should use String, because String objects are cached in an object pool and might deliver better performance when you don't change them.

    A StringBuilder is only useful when you keep on concatenating String tokens, which shouldn't be the case in a well normalized database table.

    The JVM does all sorts of optimizations and chances are that even if you use concatenation the JVM might rewrite that routine to a StringBuilder version.