Java String trim: Remove Leading and Trailing Whitespace
Java's String.trim() removes leading and trailing ASCII whitespace. See how it works, its edge cases, and how it differs from strip() in Java 11+.

When you need to remove leading and trailing whitespace from a string in Java, the trim() method is usually the first tool developers reach for. It is simple to call, but its exact behavior and limitations are easy to misunderstand. This article explains what trim() does, how it handles different kinds of whitespace, and where it falls short compared to newer alternatives.
What String.trim() Actually Does
The trim() method is defined on java.lang.String and returns a new string with leading and trailing whitespace removed. It uses a narrow definition of whitespace: any character with a code point less than or equal to the space character (' ', U+0020). That includes space, tab (\t), newline (\n), carriage return (\r), form feed (\f), and several other ASCII control characters. It does not consider Unicode whitespace such as the em space (\u2003) or no-break spaces such as \u00A0.
If no trimming is needed, trim() returns the original string instance. If trimming is needed, it returns a new string created via substring(). The original string is never modified because strings in Java are immutable.
Basic Usage and Examples
Here is the simplest form:
String input = " hello world ";
String trimmed = input.trim();
System.out.println(trimmed); // "hello world"The method removes whitespace from both ends, but it leaves internal spaces untouched. This is often exactly what you need when parsing user input, reading configuration values, or normalizing data before comparison.
Consider a more realistic scenario where you read lines from a file and want to clean them:
List<String> lines = Files.readAllLines(Paths.get("data.txt"));
List<String> cleanLines = lines.stream()
.map(String::trim)
.collect(Collectors.toList());Here, String::trim is used as a method reference, which works because trim() takes no arguments and returns a String. The stream pipeline produces a new list with each line trimmed.
Whitespace Definition and Edge Cases
Because trim() only checks for characters with code point <= ' ', it does not handle all whitespace that you might expect. For example, the non-breaking space is not removed:
String nbsp = "\u00A0hello\u00A0";
System.out.println(nbsp.trim().length()); // 7, not 5The string still contains the non-breaking spaces after trim(). This can cause subtle bugs when processing text from web pages, XML documents, or other sources that use Unicode whitespace.
Another edge case is an empty string or a string that consists entirely of removable characters. In both cases, trim() returns an empty string:
String empty = "";
String onlySpaces = " ";
System.out.println(empty.trim().isEmpty()); // true
System.out.println(onlySpaces.trim().isEmpty()); // trueThere is no special handling for null. Calling trim() on a null reference throws a NullPointerException.
trim() vs strip() in Java 11+
Java 11 introduced the strip() method, which uses Character.isWhitespace() to determine what counts as whitespace. This method is Unicode-aware and removes many Unicode whitespace characters that trim() misses, such as the em space. However, Character.isWhitespace() explicitly excludes no-break spaces, so strip() also leaves \u00A0, \u2007, and \u202F in place.
The practical difference is significant:
| Method | Whitespace definition | Removes em space (\u2003) | Removes no-break space (\u00A0) | Available since |
|---|---|---|---|---|
trim() | ASCII only (code point <= ' ') | No | No | Java 1.0 |
strip() | Unicode whitespace via Character.isWhitespace(), excluding no-break spaces | Yes | No | Java 11 |
If you are on Java 11 or later and need to handle Unicode whitespace beyond ASCII, strip() is usually the safer choice. If you need to remove no-break spaces too, strip() is not sufficient by itself; include those characters in a custom trimming routine or use a targeted replacement.
There is also stripLeading() and stripTrailing() for one-sided trimming, which trim() does not offer.
Null Handling and Common Pitfalls
The most common mistake is calling trim() on a null reference. Since trim() is an instance method, it cannot be invoked on null. Always check for null before calling it:
String value = getValue();
if (value != null) {
value = value.trim();
}Another pitfall is assuming that trim() removes all whitespace. As shown earlier, it does not handle Unicode whitespace. This can lead to inconsistent behavior when the input contains characters like \u00A0 or \u2007.
Also, remember that trim() does not change the original string. If you forget to assign the result, the original string remains untrimmed:
String s = " hello ";
s.trim(); // result is discarded
System.out.println(s); // " hello "Always use the returned value.
Performance and Allocation Behavior
From a performance perspective, trim() is efficient for typical use. It scans the string from both ends until it finds a non-whitespace character. The time complexity is O(n) in the worst case, but in practice it often stops early.
A key detail is that trim() returns the same instance if no trimming is needed. This avoids allocating a new string when the input is already clean. For example:
String clean = "hello";
String result = clean.trim();
System.out.println(result == clean); // trueWhen trimming is needed, it calls substring(), which creates a new string. Recent Java versions copy the requested range; very old versions shared the original backing array. The allocation cost is minimal for short strings.
If you are processing many strings, the main cost is the scan itself. Using strip() may be slightly more expensive because Character.isWhitespace() does more work than a simple code point comparison, but the difference is usually negligible unless you are in a tight loop.
When Not to Use trim()
There are situations where trim() is not the right tool. If you need to remove Unicode whitespace that trim() misses, use strip() on Java 11+. If you need to remove no-break spaces as well, strip() is not sufficient by itself; include those characters in a custom trimming routine or use a targeted replacement. If you need to remove only specific characters, such as quotes or commas, trim() cannot do that; you would need a custom method or a regular expression.
For example, to remove leading and trailing quotes from a string, you might do:
String quoted = "\"hello\"";
String unquoted = quoted.replaceAll("^\"|\"$", "");This uses a regex, which is more expensive than trim() but necessary for pattern-based trimming.
Another case is when you need to trim based on a custom set of characters. You can write a helper method that checks the start and end indices manually, but for most cases trim() or strip() covers the common requirement.
Using trim() with Streams and Collections
A common pattern is to trim all strings in a collection. With streams, this is concise:
List<String> raw = Arrays.asList(" apple ", " banana", "cherry ");
List<String> cleaned = raw.stream()
.map(String::trim)
.collect(Collectors.toList());This produces a new list where each element has been trimmed. If you need to trim in place, you would have to reassign each element, which streams do not support directly.
For maps, you might trim keys and values separately:
Map<String, String> map = new HashMap<>();
map.put(" key ", " value ");
Map<String, String> cleanedMap = map.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().trim(),
e -> e.getValue().trim()
));This is useful when normalizing input data before storing it in a database or using it as a lookup key.
One final note: trim() is not locale-sensitive. It always uses the same ASCII-based whitespace definition regardless of the default locale.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.