0
0
JavaHow-ToBeginner · 3 min read

How to Remove Whitespace from String in Java Easily

In Java, you can remove whitespace from a string using trim() to remove spaces at the start and end, or replaceAll("\\s+", "") to remove all whitespace inside the string. These methods help clean up strings by removing unwanted spaces.
📐

Syntax

trim(): Removes whitespace only from the beginning and end of the string.

replaceAll("\\s+", ""): Removes all whitespace characters (spaces, tabs, newlines) from the entire string.

java
String trimmed = originalString.trim();
String noSpaces = originalString.replaceAll("\\s+", "");
💻

Example

This example shows how to use trim() to remove spaces at the start and end, and replaceAll() to remove all whitespace inside the string.

java
public class RemoveWhitespaceExample {
    public static void main(String[] args) {
        String original = "  Hello  World  \t\n";
        String trimmed = original.trim();
        String noWhitespace = original.replaceAll("\\s+", "");

        System.out.println("Original: '" + original + "'");
        System.out.println("Trimmed: '" + trimmed + "'");
        System.out.println("No whitespace: '" + noWhitespace + "'");
    }
}
Output
Original: ' Hello World ' Trimmed: 'Hello World' No whitespace: 'HelloWorld'
⚠️

Common Pitfalls

  • Using trim() only removes spaces at the start and end, not inside the string.
  • To remove all spaces inside, you must use replaceAll("\\s+", "").
  • Be careful with replaceAll because it uses regular expressions, so you need to escape backslashes properly.
java
public class PitfallExample {
    public static void main(String[] args) {
        String text = "  Java  Programming  ";

        // Wrong: only trims ends
        String wrong = text.trim();

        // Right: removes all whitespace
        String right = text.replaceAll("\\s+", "");

        System.out.println("Wrong (trim): '" + wrong + "'");
        System.out.println("Right (replaceAll): '" + right + "'");
    }
}
Output
Wrong (trim): 'Java Programming' Right (replaceAll): 'JavaProgramming'
📊

Quick Reference

MethodDescriptionExample Usage
trim()Removes whitespace from start and end onlystr.trim()
replaceAll("\\s+", "")Removes all whitespace inside the stringstr.replaceAll("\\s+", "")

Key Takeaways

Use trim() to remove spaces only at the start and end of a string.
Use replaceAll("\\s+", "") to remove all whitespace characters inside the string.
Remember replaceAll uses regular expressions, so escape backslashes properly.
trim() does not remove spaces between words, only at edges.
Choose the method based on whether you want to clean edges or the entire string.