Remove All Whitespaces from a String in Java — Definition, Examples and Program

Learn how to remove all whitespaces from a string in Java using a simple character-based approach without relying on regular expressions or built-in replace methods.

Remove All Whitespaces from a String in Java

Removing whitespaces from a string means eliminating all space characters (including spaces, tabs, and new lines) and keeping only the actual content.

This operation is commonly used in input validation, data cleaning, and preprocessing user-entered text.

How the Logic Works

  1. Read the input string.
  2. Convert the string into a character array.
  3. Traverse each character one by one.
  4. If the character is not a whitespace, add it to the result.

Example 1

Input: "Java Programming"

Output: JavaProgramming

Example 2

Input: " Learn Java Fast "

Output: LearnJavaFast

Java Program to Remove All Whitespaces


import java.util.Scanner;

public class RemoveWhitespaces {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = sc.nextLine();

        String result = "";

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);

            if (ch != ' ' && ch != '\t' && ch != '\n') {
                result = result + ch;
            }
        }

        System.out.println("String without whitespaces: " + result);
    }
}

Sample Output


Enter a string: Java   is   awesome
String without whitespaces: Javaisawesome

Important Notes

Practice Challenges

  1. Modify the program to remove only extra spaces between words.
  2. Count how many whitespaces were removed.
  3. Rewrite the program using StringBuilder for better performance.

This program is a great exercise to understand how strings work internally and how to process user input efficiently in Java.