0
0
JavaHow-ToBeginner · 3 min read

How to Trim String in Java: Syntax and Examples

In Java, you can remove leading and trailing spaces from a string using the trim() method. This method returns a new string without spaces at the start or end but does not change spaces inside the string.
📐

Syntax

The trim() method is called on a string object and returns a new string with leading and trailing whitespace removed.

  • string.trim(): Returns a new string without spaces at the start and end.
java
String trimmedString = originalString.trim();
💻

Example

This example shows how to use trim() to remove spaces from the start and end of a string.

java
public class TrimExample {
    public static void main(String[] args) {
        String original = "   Hello, Java!   ";
        String trimmed = original.trim();
        System.out.println("Original: '" + original + "'");
        System.out.println("Trimmed: '" + trimmed + "'");
    }
}
Output
Original: ' Hello, Java! ' Trimmed: 'Hello, Java!'
⚠️

Common Pitfalls

One common mistake is expecting trim() to remove spaces inside the string or other whitespace characters like tabs or newlines. It only removes spaces at the start and end.

Also, trim() does not change the original string because strings in Java are immutable; it returns a new trimmed string.

java
public class TrimPitfall {
    public static void main(String[] args) {
        String text = "  Hello \t World  ";
        String trimmed = text.trim();
        System.out.println("Before trim: '" + text + "'");
        System.out.println("After trim: '" + trimmed + "'");
    }
}
Output
Before trim: ' Hello World ' After trim: 'Hello World'
📊

Quick Reference

MethodDescription
trim()Removes leading and trailing spaces from a string
strip()Removes all kinds of leading and trailing whitespace (Java 11+)
replaceAll("\\s+", "")Removes all whitespace inside the string

Key Takeaways

Use trim() to remove spaces only at the start and end of a string.
trim() returns a new string; it does not modify the original string.
trim() does not remove spaces inside the string or other whitespace characters like tabs.
For more whitespace types, consider strip() in Java 11 or later.
To remove all whitespace inside a string, use replaceAll("\\s+", "").