In this tutorial, you will learn about String trim() method, its syntax, and usage with examples.

Java String trim() method

In Java, String trim() method returns a new string with the whitespace characters trimmed from the edges of the original string.

Syntax of trim()

The syntax to call String trim() method in Java is

</>
Copy
string.trim()

trim() method takes no parameters.

trim() returns value of String type.

Examples

1. trim() – Trim spaces for given string in Java

In this example, we take a string value in str, with whitespace characters present at the edges of the string, and then trim the whitespaces from the edges of this string using String trim() method.

Java Program

</>
Copy
public class Main {
	public static void main(String[] args) {
		String str = "   Hello Wolrd         ";
		String trimmedStr = str.trim();
		
		System.out.println("Given string   : \"" + str + "\"");
		System.out.println("Trimmed string : \"" + trimmedStr + "\"");
	}
}

Output

Given string   : "   Hello Wolrd         "
Trimmed string : "Hello Wolrd"

2. trim() – Trim spaces (tabs and new lines) for given string in Java

In this example, we take a string value in str, with whitespace characters like tab and new lines present at the edges of the string, and then trim these whitespaces from the edges of this string using String trim() method.

Java Program

</>
Copy
public class Main {
	public static void main(String[] args) {
		String str = " \t\t\n  Hello Wolrd      \n\n";
		String trimmedStr = str.trim();
		
		System.out.println("Given string   : \"" + str + "\"");
		System.out.println("Trimmed string : \"" + trimmedStr + "\"");
	}
}

Output

Given string   : " 		
  Hello Wolrd      

"
Trimmed string : "Hello Wolrd"

Conclusion

In this Java String Methods tutorial, we have seen about String trim() method in Java, its syntax, and how to use String trim() method in Java programs with the help of examples.