Course contentsShow
← Java
Lesson 2212 of 2,87043. String Handling in DepthFree lesson

trim() vs strip(): Whitespace Removal Differences

Compare trim() (removes ASCII whitespace) with strip() (removes Unicode whitespace) introduced in Java 11.

trim() vs strip(): Whitespace Removal Differences

What you'll learn: You'll discover why Java offers two methods for removing whitespace and when each one matters.

The Core Difference

Both trim() and strip() remove leading and trailing whitespace from strings, but they differ in which characters they consider "whitespace":

  • trim() (legacy method) only recognizes ASCII whitespace characters (specifically, any character with a code point ≤ U+0020, which is the space character).
  • strip() (introduced in Java 11) recognizes all Unicode whitespace characters, making it internationally aware.

Think of trim() as an old tool built when text was mostly English, while strip() is the modern, globally-aware upgrade that handles text from any language or script.

Why This Matters

Unicode includes many whitespace characters beyond the basic space, tab, and newline:

  • Non-breaking spaces (U+00A0)
  • Zero-width spaces (U+200B)
  • Ideographic spaces used in Chinese/Japanese text (U+3000)

If your string contains these Unicode whitespace characters, trim() will leave them untouched, but strip() will remove them correctly.

String text = "\u2000Hello\u2000";  // U+2000 is EN QUAD (Unicode whitespace)

String trimmed = text.trim();
String stripped = text.strip();

System.out.println("[" + trimmed + "]");   // Still has whitespace: [  Hello  ]
System.out.println("[" + stripped + "]");  // Properly cleaned: [Hello]

Related Methods

Java 11 also added stripLeading() and stripTrailing() for removing whitespace from just one end—more flexible than trim().

Key Takeaway: Use strip() in modern Java code for proper Unicode whitespace handling; trim() only removes basic ASCII whitespace and can miss international characters.