Java Programming Examples Tutorial Index
Java String Programs

This Java program removes spaces from the string entered by the user. It checks for and removes all blank characters using a regular expression and prints the final output to the screen.

Example Java Program:
import java.util.Scanner;

public class RemoveSpaces {

    public static void main(String[] args) {
        Scanner obj = new Scanner(System.in); /* create a object */

        /* Taking user input */
        System.out.print("Enter some text: ");
        String sentence = obj.nextLine();

        /* Check and remove all spaces. */
        sentence = sentence.replaceAll("\\s", "");
        System.out.println("Text after removing spaces: " + sentence);
    }
}

Program Output:

Enter some text: W3 S c h o o l s
Text after removing spaces: W3Schools