Java 25 (LTS) reference · String Methods

Java String strip() Method

Remove leading and trailing whitespace, including Unicode spaces. Prefer it to the older trim().

Java 25 (LTS) Since Java 11

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.strip()

Return value

A new String.

Examples

Trim both ends or one
public class Main {
    public static void main(String[] args) {
        String raw = "   [email protected]  ";
        System.out.println("[" + raw.strip() + "]");
        System.out.println("[" + raw.stripLeading() + "]");
        System.out.println("[" + raw.stripTrailing() + "]");
    }
}

Run this on your computer — see “Get Started” for setup.

strip() vs trim()
public class Main {
    public static void main(String[] args) {
        String s = "\u2003padded\u2003";  // an em space
        System.out.println("trim:  [" + s.trim() + "]");
        System.out.println("strip: [" + s.strip() + "]");
    }
}

Output

trim:  [ padded ]
strip: [padded]

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 11Added

Was this page helpful?