Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.trim()

Removes spaces and control characters from both ends of a string.

Available since: Java 1.0

Syntax

public String trim()

Return value

StringA new string without leading and trailing spaces.

Examples

Spaces inside the string stay:

void main() {
    String input = "   Anna Smith  ";
    IO.println("[" + input.trim() + "]");
}

Output:

[Anna Smith]

Notes

trim() only removes characters with codes up to 32 (space, tab, line breaks). It leaves the non-breaking space and other Unicode spaces — prefer strip() in new code.

See also

  • String.strip() — Removes any Unicode whitespace from both ends of a string.
  • String.isBlank() — Checks whether a string is empty or contains only whitespace.

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.