Java Program to Remove All Whitespaces from a String

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Program to Remove All Whitespaces

Output

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

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

To learn more, visit Java String replaceAll().

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).


Example 2: Take string from users and remove the white space

Output

Enter the string
J  av  a-  P rog  ram  m ing
Original String: J  av  a-  P rog  ram  m ing
Final String: Java-Programming

In the above example, we have used the Java Scanner to take input from the user.

Here, the replaceAll() method replaces all the white spaces from the string.