The String.trim() method returns a copy of the string with all leading and trailing ASCII whitespace characters (code points <= 'U+0020') removed.
Whitespace Stripping & Sanitization: It removes ASCII spaces, tabs ( ), line feeds (
), and carriage returns () without modifying interior spaces. For Unicode-aware whitespace removal, explore modern Java's strip(). To measure string reduction, see length(). For replacement rules, see replace(), or slice text with substring().
The trim() method is defined in java.lang.String:
// Formal signature of String.trim() in java.lang.String
public String trim()
| Signature Element | Type | Operational Rule |
|---|---|---|
| Parameters | None | Takes no arguments; operates directly on the calling string instance. |
| Return Value | String |
A new String without outer ASCII whitespace, or this if no spaces exist. |
| Exception | Runtime | Throws NullPointerException if the invoking variable is null. |
Calling trim() strips outer spaces while leaving internal characters unaffected:
String str = " plus2net ";
System.out.println("Original length: [" + str + "] -> " + str.length()); // 14
String trimmed = str.trim();
System.out.println("Trimmed output: [" + trimmed + "] -> " + trimmed.length()); // 8Terminal Output:
Original length: [ plus2net ] -> 14
Trimmed output: [plus2net] -> 8
Java defines whitespace in trim() as any character with an ASCII code point <= 32 (U+0020):
| Escape Code | ASCII Decimal | Unicode Value | Character Description |
|---|---|---|---|
\t |
9 | U+0009 |
Horizontal Tab |
\n |
10 | U+000A |
Line Feed (Newline) |
\f |
12 | U+000C |
Form Feed |
\r |
13 | U+000D |
Carriage Return |
' ' |
32 | U+0020 |
Standard Space Character |
// String containing leading tabs, carriage returns, and trailing spaces
String messy = "\t\r\n Java Basics \t\n";
System.out.println("Before trim length: " + messy.length()); // 19
String cleaned = messy.trim();
System.out.println("After trim length: " + cleaned.length()); // 11
System.out.println("Cleaned text: [" + cleaned + "]");Terminal Output:
Before trim length: 19
After trim length: 11
Cleaned text: [Java Basics]
A common misunderstanding is that trim() removes all spaces. It only touches outer edges. To collapse multiple interior spaces, combine trim() with regex replacement:
| Operation | Code Expression | Result on " A B " |
|---|---|---|
| Outer Trim Only | str.trim() |
"A B" |
| Remove All Spaces | str.replace(" ", "") |
"AB" |
| Collapse Interior Spaces | str.trim().replaceAll("\\s+", " ") |
"A B" |
String title = " Java String Tutorial ";
// 1. trim(): only strips outer spaces; interior spaces remain intact
String trimmed = title.trim();
System.out.println("Trimmed: [" + trimmed + "]");
// 2. replaceAll(): collapse multiple interior spaces into a single space
String normalized = trimmed.replaceAll("\\s+", " ");
System.out.println("Normalized: [" + normalized + "]");Terminal Output:
Trimmed: [Java String Tutorial]
Normalized: [Java String Tutorial]
In Java 11+, the strip() family was introduced to properly handle international Unicode spaces:
| Method | Target Whitespace | Java Version Availability |
|---|---|---|
str.trim() |
ASCII characters <= 'U+0020'. |
Java 1.0+ (Universal compatibility). |
str.strip() |
All Unicode whitespace (via Character.isWhitespace). |
Java 11+ (Modern recommendation). |
str.stripLeading() |
Unicode whitespace at start only. | Java 11+. |
str.stripTrailing() |
Unicode whitespace at end only. | Java 11+. |
// Non-breaking space (\u00A0 is ASCII 160, outside ASCII 0..32)
String nbText = "\u00A0 Hello World \u00A0";
// trim() DOES NOT remove Unicode non-breaking space (leaves \u00A0 intact)
System.out.println("trim() length: " + nbText.trim().length()); // 15
// strip() (Java 11+) removes ALL Unicode whitespace
System.out.println("strip() length: " + nbText.strip().length()); // 11Terminal Output:
trim() length: 15
strip() length: 11
Calling trim() on a null reference throws a NullPointerException. Here is the canonical safe pattern for testing whether input is empty or whitespace-only:
String userInput = " ";
// SAFE PATTERN: Validating text is non-null and not empty after trimming
public static boolean isBlankInput(String s) {
return s == null || s.trim().isEmpty();
}
System.out.println("Is ' ' blank? " + isBlankInput(userInput)); // true
System.out.println("Is null blank? " + isBlankInput(null)); // true
System.out.println("Is 'data' blank? " + isBlankInput("data")); // falseTerminal Output:
Is ' ' blank? true
Is null blank? true
Is 'data' blank? false
When parsing comma-separated files, fields often contain unwanted surrounding spaces:
String csvLine = " John Doe , 28 , Software Engineer ";
String[] tokens = csvLine.split(",");
for (int i = 0; i < tokens.length; i++) {
tokens[i] = tokens[i].trim();
System.out.println("Field " + (i + 1) + ": [" + tokens[i] + "]");
}Terminal Output:
Field 1: [John Doe]
Field 2: [28]
Field 3: [Software Engineer]
Writing str.trim(); does not modify str in place. Because strings are immutable, you must reassign or capture the result: str = str.trim();.
HTML entities like generate non-breaking spaces (\u00A0, code point 160). Because 160 > 32, trim() ignores them completely. In modern Java, use strip() or replace \u00A0 explicitly.
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringTrimFullDemo {
public static void main(String[] args) {
String padded = " Welcome to plus2net ";
// 1. Verify trimming removes leading and trailing spaces
String result = padded.trim();
if (result.equals("Welcome to plus2net")) {
System.out.println("Check 1 Passed: Outer whitespace stripped successfully.");
}
// 2. Verify length delta
if (padded.length() - result.length() == 4) {
System.out.println("Check 2 Passed: Exact 4 padding spaces removed.");
}
// 3. Verify clean string returns same instance
String clean = "plus2net";
if (clean.trim() == clean) {
System.out.println("Check 3 Passed: String with no spaces returns exact instance.");
}
System.out.println("All String.trim() unit tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Outer whitespace stripped successfully.
Check 2 Passed: Exact 4 padding spaces removed.
Check 3 Passed: String with no spaces returns exact instance.
All String.trim() unit tests passed successfully!
No. If the string has no leading or trailing whitespace, trim() returns this (the same object reference) without allocating new memory.
Use replace(" ", "") or regex replaceAll("\s+", "").
No. trim() only strips whitespace characters <= 'U+0020'. To remove specific characters, use substring() or regex.
If using Java 11 or newer, prefer strip() because it properly recognizes all Unicode whitespace standards.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.