Java Program to Delete all Spaces from a String

  • Java program to remove all space characters from a string using replaceAll() method.

In this java program, we have to delete all occurrences of space characters from a given string and then print it on screen.

For Example,
Input String : Tech Crash Course
Output String : TechCrashCourse

Java program to remove all spaces from string using replaceAll method

In this java program, we will first take a string as input from user and store it in a String object "str". To delete all space characters from str, we will call replaceAll() method of String class. This method replaces any occurrence of space characters(including multiple adjacent space characters) with "". We are using "[ ]" regular expression, which matches with any space character.


import java.util.Scanner;

 * Java Program to remove all spaces from String
public class DeleteSpaces {
    public static void main(String args[]) {
        String str, output;
        Scanner scanner = new Scanner(;

        System.out.println("Enter a String");
        str = scanner.nextLine();

        // Deleting all space characters from given string
        // usnig replaceAll method
        output = str.replaceAll("[ ]", "");

        System.out.println("Output String\n" + output);
Enter a String
I love  Java  Programming
Output String
Enter a String
Java Programm     to remove spaces
Output String