w3resource
Java Programming Exercies

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

Java String: Exercise-31 with Solution

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

Pictorial Presentation:

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

Sample Solution:

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);
    }
}

Sample Output:

Original String:  Java Exercises                                                                              
New String: Java Exercises

Flowchart:

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

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to convert all the characters in a string to uppercase.
Next: Java Date, Time and Calendar Exercises

What is the difficulty level of this exercise?