Java String trim() example

In this guide, you will learn about the String trim() method in Java programming and how to use it with an example.

1. String trim() Method Overview

Definition:

The trim() method of Java's String class removes any leading and trailing whitespace from the given string. It is particularly useful when processing user input or reading text from files where unexpected white spaces might exist.

Syntax:

str.trim()

Parameters:

None.

Key Points:

- The method returns a newly allocated string and does not modify the original string.

- In Java, the characters considered as whitespace are those for which the Character.isWhitespace() method returns true.

- With the release of Java 11, a new method strip() has been introduced, which also trims leading and trailing white spaces but considers a wider range of white space characters defined by Unicode.

2. String trim() Method Example

public class TrimExample {
    public static void main(String[] args) {
        String sample1 = "   Java Programming   ";

        // Remove leading and trailing white spaces
        String trimmed1 = sample1.trim();
        System.out.println("Before trim: [" + sample1 + "]");
        System.out.println("After trim: [" + trimmed1 + "]");

        // Showing the limitation of trim
        String sample2 = " Java ";  // using non-breaking space (not removed by trim)
        System.out.println("Before trim with non-breaking space: [" + sample2 + "]");
        System.out.println("After trim with non-breaking space: [" + sample2.trim() + "]");
    }
}

Output:

Before trim: [   Java Programming   ]
After trim: [Java Programming]
Before trim with non-breaking space: [ Java ]
After trim with non-breaking space: [ Java ]

Explanation:

In the example:

1. The first usage of trim() effectively removes the leading and trailing white spaces from " Java Programming " to produce "Java Programming".

2. The second example highlights a limitation of the trim() method. The non-breaking space (often used in HTML as  ) is not considered whitespace by the trim() method and hence remains unaffected. This demonstrates cases where trim() may not behave as expected with certain Unicode whitespace characters.

Related Java String Class method examples

Comments