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
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.