StringBuilder

Repeated string changes create many temporary String objects because strings are immutable. StringBuilder holds text that can change in place.

Its methods return the same builder, so calls such as append can be chained. Convert or print the builder when the text is ready.

Build text in place

public class Main {
    public static void main(String[] args) {
        StringBuilder address = new StringBuilder("example.com");
        address.insert(0, "https://");
        address.append("/learn");
        System.out.println(address);

        StringBuilder status = new StringBuilder("Draft v2");
        status.replace(0, 5, "Final");
        System.out.println(status);
    }
}

Output:

https://example.com/learn
Final v2

The first builder inserts the protocol at the start and appends a path at the end. The second uses replace(start, end, text), which swaps the characters from start up to but not including end; positions 0 through 4 hold Draft, so the end index is 5. Unlike String's replace(old, new), the builder version works by index.

StringBuilder is designed for text construction. Keep using String when you have a finished value that should not change.

Append the item count to the builder, then replace Items with Cart.