Skip to content
Related Articles

Related Articles

Improve Article

Java String trim() method with Example

  • Difficulty Level : Basic
  • Last Updated : 04 Dec, 2018

The java lang.string.trim()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.


public String trim()  
The method accepts no parameters. 

It returns the omitted string with no leading and trailing spaces.

Example: To show the working of string trim() function.

// 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  "
    // trims the leading spaces 
    s = " Chetna loves reading books"


geeks for geeks has all java functions to read
Chetna loves reading books

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :