strip(), trim() and isBlank()

Remove leading and trailing whitespace and test for whitespace-only input, and know why strip() and isBlank() beat trim() for Unicode text.

Signature
public String strip()
  • Added in Java Java 11

Return value

StringA String with all leading and trailing white space removed, as defined by Character.isWhitespace. Returns this String if there is none.

Errors

Nothing. Calling it on a null reference throws NullPointerException.

Input from forms, headers, CSV files and environment variables often carries stray spaces, tabs or a trailing newline. Java has two generations of methods for cleaning them up.

MethodSinceWhat counts as whitespace
trim()Java 1.0any char with a code of U+0020 or less (space and ASCII control chars)
strip(), stripLeading(), stripTrailing()Java 11Character.isWhitespace, which includes Unicode spaces such as U+2003 and U+3000
isBlank()Java 11true if empty or only Character.isWhitespace chars
isEmpty()Java 6true only if length() == 0

Prefer strip()

Text copied from documents, chat apps or East Asian keyboards can contain an em space or ideographic space. trim() leaves those in place, so a lookup by email or SKU fails for a reason nobody can see. strip() removes them. trim() also strips ASCII control chars, which strip() only does for those Java counts as whitespace, so the two are not drop-in identical, but for user input strip() is the better default.

The no-break space

U+00A0, the no-break space that HTML   produces, is not whitespace to Character.isWhitespace. Neither trim() nor strip() removes it, and isBlank() returns false for it. If your input comes from web pages or spreadsheets, replace it with a normal space first.

Validation pattern

Check null, then isBlank() for required fields, then store the strip()ped value. isEmpty() alone lets " " through as a name. Remember the result is a new String: name.strip(); on its own line does nothing.

None of these touch whitespace in the middle of the text. To collapse inner runs of spaces, use replaceAll("\\s+", " ").

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Rejecting a signup whose name is only spaces with a 400 response.
  • Normalising an email address pasted with a trailing newline before looking it up.
  • Reading environment variables and config lines that may carry stray whitespace.

Frequently asked questions

What is the difference between strip() and trim() in Java?

trim() removes chars with codes up to U+0020, which covers ASCII spaces and control chars. strip() (Java 11) removes chars for which Character.isWhitespace is true, which includes Unicode spaces such as U+2003 and U+3000. Prefer strip() for user input.

What is the difference between isEmpty() and isBlank()?

isEmpty() is true only when length() is 0. isBlank() (Java 11) is also true when the String contains only whitespace, so " ".isBlank() is true but " ".isEmpty() is false.

Why does strip() not remove a non-breaking space?

Character.isWhitespace returns false for U+00A0 by design, so strip(), trim() and isBlank() all treat it as content. Replace it with a regular space first.

More examples

Required fields in a request

isBlank catches spaces and tabs that isEmpty would accept, and the null check runs first so the method call never throws. A handler can return all the errors in one 400 response.

Example · java
record Signup(String name, String email) {}

List<String> validate(Signup s) {
    List<String> errors = new ArrayList<>();
    if (s.name() == null || s.name().isBlank()) errors.add("name is required");
    if (s.email() == null || s.email().isBlank()) errors.add("email is required");
    return errors;
}

void main() {
    IO.println(validate(new Signup("Ada", "[email protected]")));
    IO.println(validate(new Signup("   ", "\t")));
    IO.println(validate(new Signup(null, " [email protected] ")));
}
// Output:
// []
// [name is required, email is required]
// [name is required]

Cleaning lines from a config file

lines() splits on any line terminator, strip removes the indentation and the trailing spaces kept by the \s escapes, and isBlank drops empty lines. Comments are skipped after stripping, so indented comments are caught too.

Example · java
void main() {
    String file = """
            # settings
              port = 8080\s\s

            host=localhost
            """;
    file.lines()
            .map(String::strip)
            .filter(l -> !l.isBlank() && !l.startsWith("#"))
            .forEach(l -> IO.println("[" + l + "]"));
}
// Output:
// [port = 8080]
// [host=localhost]

strip versus trim on non-ASCII spaces

strip removes the ideographic space that trim keeps. Neither removes the no-break space, so it is replaced with a plain space before stripping, which is the fix for IDs pasted from a web page or spreadsheet.

Example · java
void main() {
    String ideographic = "\u3000order-42\u3000";
    String nbsp = "\u00A0order-42\u00A0";
    IO.println(ideographic.trim().length() + " " + ideographic.strip().length());
    IO.println(nbsp.trim().length() + " " + nbsp.strip().length());

    String cleaned = nbsp.replace('\u00A0', ' ').strip();
    IO.println(cleaned.length() + " " + cleaned);
}
// Output:
// 10 8
// 10 10
// 8 order-42

Discussion

  • Be the first to comment on this lesson.