Skip to Content

Java String Trim Example

  1. /*
  2.         Java String Trim Example.
  3.         This Java String trim example shows how to remove leading and trailing space
  4.         from string using trim method of Java String class.
  5. */
  6.  
  7. public class RemoveLeadingTrailingSpace {
  8.  
  9.         public static void main(String[] args) {
  10.                
  11.                 String str = "   String Trim Example   ";
  12.                
  13.                 /*
  14.                  * To remove leading and trailing space from string use,
  15.                  * public String trim() method of Java String class.
  16.                  */
  17.                  
  18.                  String strTrimmed = str.trim();
  19.                  
  20.                  System.out.println("Original String is: " + str);
  21.                  System.out.println("Removed Leading and trailing space");
  22.                  System.out.println("New String is: " + strTrimmed);
  23.         }
  24. }
  25.  
  26. /*
  27. Output would be
  28. Original String is:    String Trim Example  
  29. Removed Leading and trailing space
  30. New String is: String Trim Example
  31. */