🔹 1️⃣ String.trim()
The classic method for removing whitespace from both ends of a string.
Syntax:
String trimmed = str.trim();
Behavior:
- Removes leading and trailing whitespace.
- Whitespace includes:
spaces (' '), tabs ('\t'), newlines ('\n'), carriage returns ('\r').
✅ Example:
String s = " Hello World! ";
System.out.println(s.trim());
Output:
Hello World!
🔹 2️⃣ Limitation of trim()
trim() only removes characters ≤ ‘\u0020’ (space).
It does not handle all Unicode whitespace characters (like non-breaking spaces).
Example:
String s = "\u00A0Hello\u00A0"; // non-breaking spaces
System.out.println(s.trim().equals("Hello")); // false
🔹 3️⃣ String.strip() — Modern Alternative (Java 11+)
Introduced in Java 11, strip() is Unicode-aware and replaces trim() for most modern uses.
Syntax:
String result = str.strip();
Behavior:
- Removes all Unicode whitespace (not just ASCII).
- Uses
Character.isWhitespace()to decide what counts as whitespace.
✅ Example:
String s = "\u2003 Hello World! \u2003"; // contains em space
System.out.println(s.strip());
Output:
Hello World!
🔹 4️⃣ Related Methods (Java 11+)
| Method | Description | Example | Result |
|---|---|---|---|
strip() | Removes both leading and trailing Unicode whitespace | " hi ".strip() | "hi" |
stripLeading() | Removes only leading whitespace | " hi ".stripLeading() | "hi " |
stripTrailing() | Removes only trailing whitespace | " hi ".stripTrailing() | " hi" |
🔹 5️⃣ Comparison Table
| Feature | trim() | strip() |
|---|---|---|
| Introduced | Java 1.0 | Java 11 |
| Removes | ASCII spaces (≤ \u0020) | All Unicode whitespace |
| Unicode-aware | ❌ No | ✅ Yes |
| Use for modern code | ⚠️ Not recommended | ✅ Preferred |
🔹 6️⃣ Example Comparison
String s = "\u2002Java\u2002"; // contains en-space (U+2002)
System.out.println("[" + s.trim() + "]"); // [ Java ]
System.out.println("[" + s.strip() + "]"); // [Java]
✅ strip() works correctly with all Unicode whitespaces.
🔹 7️⃣ Summary
| Method | Description | Java Version |
|---|---|---|
trim() | Removes ASCII whitespace | 1.0 |
strip() | Unicode-aware trimming | 11 |
stripLeading() | Remove only start whitespace | 11 |
stripTrailing() | Remove only end whitespace | 11 |
💡 Best practice:
Always use
strip()in modern Java (11+) unless you specifically need the oldtrim()behavior.
