trim() String Example


java.lang.String class comes with trim() String method to remove both leading and trailing whitespaces in the string. After trimming, a new string is returned.

The signature of trim() String is given as defined in Java API.

  • public String trim(): Returns a new string after deleting both prefix and suffix whitespaces in the given string. Original string is not disturbed.
In the following example, trim() String is used to trim the string oldString.

Observe the screenshot, the original string oldString is not disturbed.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String oldString = " hello ";                  // observe, one prefix and one suffix spaces

  String newString = oldString.trim();           // see usage of trim() String

  System.out.println("Length of old sring before trim called: " + oldString.length());
  System.out.println("Length of new string returned after trim: " + newString.length());
  System.out.println("Length of old sring after trim called: " + oldString.length());
 }
}


trim() String
Output screenshot on trim() String Example

Pass your comments and suggestions, for improvement, on this tutorial "trim() String Example".

Leave a Comment

Your email address will not be published.