Strings in Java

By Khanh Pham

Immutability

String instances have immutable values, i.e., their values cannot be changed after created.

String pool

String pool is one of the special constant pools maintained by the JVM. This pool keeps track of all the string literals used in the application.

When a new String instance is created by the string literal, e.g., String s = "hello";, the JVM looks into the pool to see if the same string literal has been created. If found, the JVM assigns the shared String object for the literal to the new instance, otherwise it records the new literal into the pool, creates a new String object, and assigns the new object to the new instance. This whole process is called string interning, and it can be enforced by calling String#intern() method.

However, string interning will not be applied if a String instance is created by the new operator, e.g., String s = new String("hello");, in which case a new String object is always created.

String concatenation

  • The overloading + vs. StringBuilder

    Under the hood, the compiler automatically creates a StringBuilder when the overloading + is used to concatenate strings. But it is not smart enough to reuse the StringBuilder, for example, when the concatenation happens inside a loop, in which case it creates a new StringBuilder for each iteration. This is the main reason why StringBuilder is preferred over the overloading + operator.

  • StringBuilder vs. StringBuffer

    • Provide same API
    • StringBuffer guarantees thread-safety by synchronizing all of its operations, while StringBuilder does not.
    • StringBuilder offers a better performance because no synchronization is involved.

References

[1] Thinking in Java

[2] OCA/OCP Java® SE 7 Programmer I & II Study Guide (Exams 1Z0-803 & 1Z0-804)

[3] http://java-performance.info/string-intern-in-java-6-7-8/

[4] http://javatechniques.com/blog/string-equality-and-interning/