w3resource logo


Java Programming Exercies

Java String Exercises: Trim any leading or trailing whitespace from a given string

Secondary Nav

Java String : Exercise-31 with Solution

Write a Java program to trim any leading or trailing whitespace from a given string.

Java Code:

public class Exercise31 {

public static void main(String[] args)
    {
        String str = " Java Exercises ";

        // Trim the whitespace from the front and back of the
        // String.
        String new_str = str.trim();

        // Display the strings for comparison.
System.out.println("Original String: " + str);
System.out.println("New String: " + new_str);
    }
}

Output:

Original String:  Java Exercises                                        
New String: Java Exercises

Java Practice online:

public class Exercise31 {

public static void main(String[] args)
    {
        String str = " Java Exercises ";

        // Trim the whitespace from the front and back of the
        // String.
        String new_str = str.trim();

        // Display the strings for comparison.
System.out.println("Original String: " + str);
System.out.println("New String: " + new_str);
    }
}



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program