Join our newsletter for the latest updates.

Java String trim()

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

The syntax of the string trim() method is:


Here, string is an object of the String class.

trim() Parameters

  • the trim() method doesn't take any parameters

trim() Return Value

  • returns a string with leading and trailing whitespace removed
  • If there are no whitepace in the start or the end, it returns the original string.

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 = "     Learn   Java Programming ";
    String str2 = "Learn\nJava Programming\n\n   ";



Learn  Java Programming
Java Programming

Here, str1.trim() returns

"Learn   Java Programming"

Similarly, str2.trim() returns

"Learn\nJava Programming"

As you can see from the above example, the trim() method only removes the leading and trailing whitespace. It doesn't remove whitespace the appear in the middle.

Remove All Whitespace Characters

If you need to remove all whitespace characters from a string, you can use the String replaceAll() method with proper regex.

class Main {
  public static void main(String[] args) {
    String str1 = "Learn\nJava \n\n   ";
    String result;

    // replace all whitespace characters with empty string
    result = str1.replaceAll("\\s", "");
    System.out.println(result);  // LearnJava
Did you find this article helpful?