Skip to content
Related Articles

Related Articles

Improve Article

Java String trim() method with Example

  • Difficulty Level : Basic
  • Last Updated : 25 Sep, 2021

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is ‘\u0020’. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. The trim() method also helps in trimming the characters in Java.

Note: The trim() method doesn’t eliminate middle spaces.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Method Signature:



public String trim()

Parameters: The trim() method accepts no parameters. 

Return Type: The return type of trim() method is String. It returns the omitted string with no leading and trailing spaces. 

Below are examples to show the working of the string trim() method in Java. 

Example 1:

Java




// Java program to demonstrate working
// of java string trim() method
 
class Gfg {
 
    // driver code
    public static void main(String args[])
    {
 
        // trims the trailing and leading spaces
        String s = " geeks for geeks has all java functions to read  ";
        System.out.println(s.trim());
 
        // trims the leading spaces
        s = " Chetna loves reading books";
        System.out.println(s.trim());
    }
}
Output
geeks for geeks has all java functions to read
Chetna loves reading books

Example 2:

Java




// Java program to demonstrate working
// of java string trim() method
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
         
      String s1 = "   Geeks For Geeks   ";
       
      // Before Trim() method
      System.out.println("Before Trim() - ");
      System.out.println("String - "+s1);
      System.out.println("Length - "+s1.length());
       
      // applying trim() method on string s1
      s1=s1.trim();
       
      // After Trim() method
      System.out.println("\nAfter Trim() - ");
      System.out.println("String - "+s1);
      System.out.println("Length - "+s1.length());
       
    }
}
Output
Before Trim() - 
String -    Geeks For Geeks   
Length - 21

After Trim() - 
String - Geeks For Geeks
Length - 15



My Personal Notes arrow_drop_up
Recommended Articles
Page :