Java String trim() method

The trim() method in Java is used to remove leading and trailing whitespace (spaces, tabs, and other whitespace characters) from a string. However, it does not remove whitespace between words or characters inside the string.

Syntax:


public String toLowerCase() 

Note:

  • It returns a new string with the leading and trailing whitespace removed. If there is no leading or trailing whitespace, the original string is returned unchanged.

Example:


public class Main {
    public static void main(String[] args) {
        // Example string with leading and trailing spaces
        String str = "   How r you?   ";
        
        // Trim leading and trailing whitespace
        String trimmedStr = str.trim();
        
        System.out.println("Original String: '" + str + "'");  // Output: '   How r you?   '
        System.out.println("Trimmed String: '" + trimmedStr + "'");  // Output: 'How r you?'
    }
}

Output:

Original String: ‘   How r you?   ‘
Trimmed String: ‘How r you?’

If string contain only spaces

If the string contains only spaces (or whitespace characters), the trim() method will return an empty string.


public class Main {
    public static void main(String[] args) {
        // Example string with leading and trailing spaces
        String str = "   ";
        String trimmedStr = str.trim();
        System.out.println(trimmedStr);  // Output: ''
    }
}