Because String is immutable, concatenating strings inside a loop (str += i) creates thousands of temporary garbage objects. Choose the right class:
String: Immutable, stored in String Pool. Best for constants and infrequent edits.StringBuilder: Mutable, not synchronized (fastest). Best for building strings in single-threaded loops.StringBuffer: Mutable, synchronized (thread-safe, slightly slower). Best when multiple threads modify the same buffer.
ADVERTISEMENT