Java .trim()

Anonymous contributor's avatar
Anonymous contributor
Published Feb 13, 2023
Contribute to Docs

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

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

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!

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours