Chapter 3 · Simulation

String Pool and StringBuilder

← Chapter 3
Correct 0 / 0

Java code

    Memory

    Output (console)

    String Pool and StringBuilder

    Purpose: see how Java keeps strings in memory. String literals such as "Java" in the source code are kept in a special region of the heap, the string pool, and literals with the same content share one object. String is immutable: every "change" creates a new object. StringBuilder, on the other hand, modifies the same buffer in place.

    How to use it

    1. Pick a program from the list; use Step ▶ / ◀ (→ / ← on the keyboard), Play, Reset.
    2. On the left is the main frame on the stack; on the right is the heap: the region with the green dashed outline is the string pool. A newly created object has a red outline; an unreachable object is faded and dashed (eligible for garbage collection).
    3. While Try it yourself is on, you predict each println output in advance.

    Reminders

    • == checks whether two references point to the same object; equals compares the contents. Always compare strings with equals.
    • new String("Java") creates a new object, independent of the literal in the pool. s.intern() returns its equivalent in the pool.
    • Expressions that can be computed at compile time ("Ja" + "va", concatenation with a final variable) become a single literal and go to the pool; a + with a variable at run time creates a new object.
    • Methods such as s.toUpperCase() do not change s; to use the result you have to assign it: s = s.toUpperCase();
    • A StringBuilder has a length (length) and a buffer size (capacity); for new StringBuilder("Ja") the capacity is 16 + 2 = 18. For concatenation in a loop, use StringBuilder instead of String +.

    The object numbers (#1, #2…) are for explanation only. Exactly when a literal is added to the pool depends on the JVM; here it is shown at the line where it is first used. All outputs were verified by compiling with javac --release 8 and running on Java 8.

    Related slides: Chapter 3.4 · Strings (Comparing with ==, The String Pool, Pool Step by Step, Immutability, StringBuilder).