Java String.trim() Method Example

1. Introduction

The String.trim() method in Java is used to remove leading and trailing whitespace from a string. This method is commonly used in processing user input, data cleansing, and formatting outputs where unwanted spaces may affect data processing or comparisons. This tutorial will demonstrate how to use the trim() method effectively.

Key Points

- trim() removes both leading and trailing whitespace from a string.

- It does not alter the internal spacing of the string.

- The method returns a new string, leaving the original string unchanged.

2. Program Steps

1. Declare a string with extra spaces at the beginning and end.

2. Use trim() to remove these spaces.

3. Print the original and trimmed string.

3. Code Program

public class StringTrimExample {
    public static void main(String[] args) {
        // Original string with leading and trailing spaces
        String original = "   Hello, Java!   ";
        // Trimmed string
        String trimmed = original.trim();
        // Print original and trimmed versions
        System.out.println("Original string: '" + original + "'");
        System.out.println("Trimmed string: '" + trimmed + "'");


Original string: '   Hello, Java!   '
Trimmed string: 'Hello, Java!'


1. String original = " Hello, Java! ": Declares and initializes a String variable original with extra spaces at the beginning and end.

2. String trimmed = original.trim(): Calls the trim() method to remove leading and trailing spaces from original, resulting in trimmed.

3. System.out.println("Original string: '" + original + "'"): Prints the original string with spaces visible.

4. System.out.println("Trimmed string: '" + trimmed + "'"): Prints the trimmed string showing the removal of spaces.