How to remove leading and trailing spaces from a string?

Question:
How can you remove all of the leading and trailing spaces in a string?

Answer:
Using the String trim() method.

Code:
public class TrimExample {
 
   public static void main(String[] args) {
 
      String str1 = "   String with spaces   ";
 
      // removing leading and trailing whitespaces. 
      String str2 = str1.trim();
 
      System.out.println("Original String: " + str1);
      System.out.println("New String     : " + str2);
   }
}

Output:
$ java TrimExample 
Original String:    String with spaces   
New String     : String with spaces