Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.trim — removing boundary characters through U+0020

String.trim removes characters with values no greater than U+0020 from both ends, leaving the interior unchanged.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public String trim()
String result = text.trim();

String.trim is a no-argument instance method returning String. It removes consecutive characters with values <= U+0020 from both ends, including spaces, tabs, and newlines. Interior text stays unchanged.

String is immutable: retain the returned result. For empty text or text needing no removal, the method returns the same reference. If every character qualifies for removal, the result is empty.

This does not remove all Unicode whitespace: U+2003 remains. The example also demonstrates preservation of two interior spaces.

Examples

public class Main {
    public static void main(String[] args) {
        String text = " \tJava  SE\n";
        String result = text.trim();
        System.out.println("[" + result + "]");
        System.out.println(" \t\n".trim().isEmpty());
        System.out.println("\u2003Java\u2003".trim().length());
    }
}

Result

[Java  SE]
true
6

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources