English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/)

Java Reader/Writer

Java Other Topics

Java String trim() usage and example

Java String (String) Methods

The Java String trim() method returns a string with any leading (beginning) and trailing (ending) spaces removed.

The syntax of the string trim() method is:

string.trim()

trim() parameter

  • trim() method without any parameters

trim() return value

  • Returns a string with leading and trailing spaces removed

  • If there are no spaces at the beginning or end, the original string is returned.

Note:In programming, whitespace is any character or series of characters that represent horizontal or vertical space. For example: space, newline \n, tab \t, vertical tab \v, etc.

Example: Java String trim()

class Main {
  public static void main(String[] args) {
    String str1 = "\t\t\tLearn\t\tJava\tProgramming";
    String str2 = "Learn\nJava Programming\n\n\t";
    System.out.println(str1.trim());
    System.out.println(str2.trim());
  }
}

Output Result

Learn Java Programming
Learn
Java Programming

Here, str1.trim() returns

"Learn\t\tJava\tProgramming"

Similarly, str2.trim() returns

"Learn\nJava\n\n\tProgramming"

From the above example, it can be seen that the trim() method only removes leading and trailing spaces. It does not remove spaces appearing in the middle.

Remove all whitespace characters

If necessaryAll whitespace characters from the stringThen you can removeString replaceAll() methodUsing appropriate regular expressions.

class Main {
  public static void main(String[] args) {
    String str1 = "Learn\nJava\n\n\t";
    String result;
    //Replace all whitespace characters with an empty string
    result = str1.replaceAll("\\s", "");
    System.out.println(result);  // LearnJava
  }
}

Java String (String) Methods