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.

trim( ) is used to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

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: ''
    }
}

Java String trim() method – Interview Questions

Q 1: What is the purpose of trim() method?

Ans: It removes leading and trailing whitespaces from a string.

Q 2: Does trim() remove spaces in the middle?

Ans: No, it only removes spaces at the beginning and end.

Q 3: What type of value does trim() return?

Ans: A new trimmed string.

Q 4: Does trim() change the original string?

Ans: No, strings are immutable.

Q 5: When is trim() commonly used?

Ans: For input validation and data cleaning.

Java String trim() method – Objective Questions (MCQs)

Q1. What does the trim() method do in Java?






Q2. What will " Hello World ".trim() return?






Q3. Does trim() modify the original string?






Q4. The trim() method is defined in which class?






Q5. What happens if you call trim() on an empty string?






Related Java String trim() method Topics