.trim()

The .trim() method removes any leading and trailing whitespace from a string.

Syntax

string.trim()

No parameters are required for the .trim() method.

Example

In the example below, the .trim() method removes leading and trailing whitespaces from the string greetings.

// Example.java
import java.io.*;
class Example {
public static void main(String[] args) {
String greetings = " Hello, Stranger! ";
System.out.println(greetings.trim());
}
}

This will produce the following output:

Hello, Stranger!

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Java on Codecademy

Contributors