Java Program to Remove All Whitespaces from a String

In this program, you’ll learn to remove all whitespaces in a given string using regular expressions in Java.

Example: Program to Remove All Whitespaces

  1. public class Whitespaces {
  2. public static void main(String[] args) {
  3. String sentence = "T his is b ett er.";
  4. System.out.println("Original sentence: " + sentence);
  5. sentence = sentence.replaceAll("\\s", "");
  6. System.out.println("After replacement: " + sentence);
  7. }
  8. }

When you run the program, the output will be:

Original sentence: T    his is b  ett     er.
After replacement: Thisisbetter.

In the aboe program, we use String’s replaceAll() method to remove and replace all whitespaces in the string sentence.

We’ve used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in the string. Then, we replace it with "" (empty string literal).