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:
| Parameter | Type | Description |
|---|---|---|
| String | Class | Immutable string pool managed character sequence. |
| StringBuilder | Class | Mutable buffer for high-performance string concatenation. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java ArrayList and Arrays: Dynamic Collections vs Fixed Arrays
Master fixed-size arrays and dynamic java.util.ArrayList with add, get, and remove.
Java Input and Output: Scanner, System.out, and printf
Read inputs using java.util.Scanner and format output streams with System.out.printf.
Java Variables and Primitive Data Types with Examples
Declare typed variables in Java including int, double, boolean, String, and local var (Java 10+).
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.