Java String trim() Method

trim():

Returns a copy of the string, with leading and trailing white space omitted.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public String trim()
public String trim()
public String trim()

 

Example

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class TestString{
String str = " www.w3schools.blog ";
public void trimString(){
//will remove all leading and trailing whitespace.
System.out.println(str.trim());
}
}
public class StringTrimExample {
public static void main(String args[]){
//creating TestString object
TestString obj = new TestString();
//method call
obj.trimString();
}
}
class TestString{ String str = " www.w3schools.blog "; public void trimString(){ //will remove all leading and trailing whitespace. System.out.println(str.trim()); } } public class StringTrimExample { public static void main(String args[]){ //creating TestString object TestString obj = new TestString(); //method call obj.trimString(); } }
class TestString{
    String str = "   www.w3schools.blog  ";
    
    public void trimString(){
        //will remove all leading and trailing whitespace. 
        System.out.println(str.trim());
    }
}

public class StringTrimExample {
    public static void main(String args[]){
        //creating TestString object
        TestString obj = new TestString();
        
        //method call
        obj.trimString();
    }
}

Output

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
www.w3schools.blog
www.w3schools.blog
www.w3schools.blog