Java:Java String Methods, StringBuilder, and Immutability
Java•Strings

Java String Methods, StringBuilder, and Immutability

Learn why Java Strings are immutable and how StringBuilder avoids intermediate allocations in loops.

Syntax

String s = "Hello"; StringBuilder sb = new StringBuilder(); sb.append("World");

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
StringClassImmutable string pool managed character sequence.
StringBuilderClassMutable buffer for high-performance string concatenation.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static void main(String[] args) {
        String rawEmail = "   [email protected]   ";
        String cleanEmail = rawEmail.trim();

        System.out.println("Clean Email: " + cleanEmail);
        String[] parts = cleanEmail.split("@");
        System.out.println("Username:    " + parts[0]);
        System.out.println("Domain:      " + parts[1]);

        // StringBuilder for high-performance concatenation
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 3; i++) {
            sb.append("Node-").append(i).append(" ");
        }
        System.out.println("Cluster:     " + sb.toString().trim());
    }
}
Expected Output:
Clean Email: [email protected]
Username:    developer
Domain:      compilra.dev
Cluster:     Node-1 Node-2 Node-3

How It Works: Step-by-Step

  • Lines 3-8: trim() cleans whitespace; split("@") partitions string into parts array.
  • Lines 12-16: StringBuilder appends parts in a single buffer without intermediate copies.

Key Concepts

  • Strings in Java are immutable; methods return new String instances.
  • Java uses a String Pool to reuse identical string literals in memory.
  • Use StringBuilder inside loops to prevent O(N^2) memory allocations.

Common Mistake: Concatenating strings with + inside large loops

Repeated + creates a new String and garbage collects the previous one on every single iteration.

❌ Incorrect
String s = ""; for (int i = 0; i < 1000; i++) { s += i; } // 1000 allocations!
✅ Correct
StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); }

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler