Java String trim() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
String

Definition

In Java, trim() returns a string with all leading and trailing characters whose code is U+0020 or lower removed. That covers the ordinary space, tabs, line breaks, and other ASCII control characters; the characters in the middle are kept.

It is the classic way to clean user input before comparing or storing it. If nothing needs to be removed, the same string object is returned. For Unicode-aware trimming, Java 11 added strip().

trim() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.trim(); calling it on a null reference throws NullPointerException. Strings are immutable, so it never changes the original: it returns a new String (or the same one when nothing changes). Keep the result.

Syntax

Call it with no arguments and use the returned string.

java
String clean = input.trim();
boolean empty = input.trim().isEmpty();
CallWhat it does
" hi ".trim()"hi".
"\tdata\n".trim()"data".
"a b".trim()"a b": inner spaces stay.

trim() knows nothing about Unicode spaces such as the em space (U+2003) or the ideographic space (U+3000); they are above U+0020, so they survive. strip() removes them.

Library declarations
java
public String trim();

Parameters

ParameterDescription
Nonetrim() takes no parameters.

Return Value

Return ValueDescription
StringThe text without leading and trailing chars up to U+0020, or this string if there are none.

Java Examples

Example 1 — Remove Padding Around Text

Brackets show exactly where the trimmed text begins and ends.

java
public class TrimBasic {
    public static void main(String[] args) {
        String padded = "   Hello World   ";
        String trimmed = padded.trim();

        System.out.println("[" + trimmed + "]");
        System.out.println(padded.length() + " -> " + trimmed.length());
    }
}

How It Works

  1. Both ends at once. The three spaces before and the three after the text are removed in one call.
  2. The middle is kept. The space between Hello and World is not at an edge, so it stays.
  3. Compare the lengths. 17 chars shrink to 11, exactly the six padding spaces fewer.

Example 2 — Accept Answers Typed with Extra Whitespace

Combine trim() with equalsIgnoreCase to accept sloppy input.

java
public class TrimInput {
    public static void main(String[] args) {
        String[] typed = {"  yes", "YES  ", "\tyes\n"};

        for (String t : typed) {
            boolean ok = t.trim().equalsIgnoreCase("yes");
            System.out.println("[" + t.trim() + "] accepted: " + ok);
        }
    }
}

How It Works

  1. Different kinds of padding. Leading spaces, trailing spaces, and a tab with a newline are all at or below U+0020.
  2. Trim, then compare. After trim() each answer is exactly three letters, and equalsIgnoreCase ignores the capitals.
  3. All accepted. Without trim(), " yes".equalsIgnoreCase("yes") would be false.

Example 3 — Control Characters Go, Unicode Spaces Stay

Test characters below and above the U+0020 limit.

java
public class TrimUnicode {
    public static void main(String[] args) {
        String enSpace = "\u2002ok\u2002";
        String bell = "\u0007ok\u0007";
        String mixed = "\t\nok\r\n";

        System.out.println("en space: length " + enSpace.trim().length());
        System.out.println("bell:     length " + bell.trim().length());
        System.out.println("mixed:    length " + mixed.trim().length());
    }
}

How It Works

  1. Above the limit. The en space U+2002 is a space to humans but its code is greater than U+0020, so trim() keeps both of them.
  2. Control chars are removed. The bell character U+0007 is not whitespace at all, yet it is below U+0020, so trim() strips it.
  3. Tabs and line breaks. \t, \n, and \r are all low ASCII codes, leaving just "ok".

Frequently Asked Questions

All leading and trailing characters with a code of U+0020 or less: spaces, tabs, line breaks, and other ASCII control characters.
No. Only the start and the end are trimmed. Use replaceAll("\\s+", " ") to collapse inner whitespace.
trim() removes chars up to U+0020. strip() (Java 11) removes characters for which Character.isWhitespace is true, including Unicode spaces such as U+3000.
Strings are immutable; trim() returns a new String. Assign it: s = s.trim();
No. If there is nothing to remove, it returns the same string object.

Next: valueOf()

Convert numbers, booleans, chars, objects, or char arrays to a String (static).

valueOf() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful