Java Program to Remove White Spaces from a String

In this Java program, we will learn how to remove white spaces from a String using three different approaches:

  1. Using Loop (Manual Method)
  2. Using replaceAll() Method
  3. Using Java 8 Stream API

For example:

Input  : Java Programming Language
Output : JavaProgrammingLanguage

1. Traditional Java Program (Using Loop)

In this approach, we manually check each character and remove spaces and tabs.

import java.util.Scanner;

public class RemoveWhiteSpace {
    public static void main(String[] args) {
        System.out.print("Enter any string : ");
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] c = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < c.length; i++) {
            if ((c[i] != ' ') && (c[i] != '\t')) {
                sb.append(c[i]);
            }
        }
        System.out.println(sb);
        sc.close();
    }
}

Explanation (Loop Method)

  • The string is converted into a character array using toCharArray().
  • Each character is checked one by one.
  • If the character is not a space or tab, it is added to StringBuffer.
  • Finally, the result is printed without spaces.

👉 This method is useful for beginners to understand character-level processing.


2. Using replaceAll() Method

This is the simplest and most commonly used approach.

import java.util.Scanner;

public class RemoveWhiteSpace {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String str = sc.nextLine();
        String result = str.replaceAll("\\s", "");
        System.out.println("String without white spaces: " + result);
        sc.close();
    }
}

Explanation (replaceAll Method)

  • replaceAll("\\s", "") removes all whitespace characters.
  • \\s represents:
    • space
    • tab
    • newline
  • "" replaces them with nothing.

👉 This is the shortest and most efficient traditional approach.


3. Java 8 Program (Using Stream API)

Java 8 provides a modern functional approach using Streams.

import java.util.Scanner;
import java.util.stream.Collectors;

public class RemoveWhiteSpaceJava8 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String str = sc.nextLine();
        String result = str.chars()
                .filter(c -> !Character.isWhitespace(c))
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining());
        System.out.println("String without white spaces: " + result);
        sc.close();
    }
}

Explanation (Java 8 Stream Method)

  • str.chars() → converts string into stream of characters
  • filter(c -> !Character.isWhitespace(c)) → removes all whitespace characters
  • mapToObj() → converts int values back to characters
  • Collectors.joining() → combines all characters into final string

👉 This method is useful for learning functional programming in Java.


Comparison of All Three Methods

FeatureLoop MethodreplaceAll()Java 8 Stream
ApproachManualBuilt-in methodFunctional
DifficultyEasyVery EasyModerate
PerformanceGoodBestGood
Code LengthLongShortMedium
Best ForBeginners learning logicReal-world useJava 8 learning

Conclusion

Removing white spaces from a String is a common Java programming task. We learned three different ways:

  • Manual loop method for understanding logic
  • replaceAll() for simple and fast solution
  • Java 8 Stream API for modern functional programming

Each method has its own importance depending on learning level and use case.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *