Java String trim example

String's trim method is used to remove leading and trailing space. Sometimes, you get extra leading or trailing space and your program does not work as expected. It returns String object after removing leading and trailing spaces.
String's trim method does not remove middle spaces.

String trim example:

package org.arpit.java2blog;

public class StringTrimExample {

 public static void main(String[] args) {
  String str = "     Hello world from    ";

  //without trim()
  System.out.println("Without trim");
  System.out.println("----------------------");
  System.out.println(str+"java2blog.com");
  System.out.println("----------------------");
  // with trim()
  System.out.println("\nWith trim");
  System.out.println("----------------------");
  System.out.println(str.trim()+"java2blog.com");
 
 }
}

When you run above program, you will get below output:
Without trim
----------------------
     Hello world from    java2blog.com
----------------------

With trim
----------------------
Hello world fromjava2blog.com


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012