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");
  // with trim()
  System.out.println("\nWith trim");

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

With trim
Hello world

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