Removing White spaces from a String in Java

Hello Folks,

Today we will learn to remove unnecessary whitespaces from a string in Java.

Remove extra whitespaces from a string in Java

So, making clear what we intend to do let’s take an example.

“Java       is       the       best      programming     language”

Now we want the above sentence to look like this:

“Java is the best programming language.”

Okay then let’s get started.

So if you remember about the Java replace method well and good, but if you don’t, no  need to worry, you can check about it in my previous tutorial here:

So the logic for our program will be to replace double whitespace with single whitespace till there are no more double whitespaces.

In each iteration, each double whitespace will be replaced by single whitespace, and in the end, we will get a string with no unnecessary whitespaces.

Here’s the complete Java Program.

Multiple whitespaces to single whitespace in java

import java.util.*;
public class test
  public static void main(String args[])
    String str="Java     is     the    best  programming      language";
    int ln=str.length();
    for(int i=0;i<ln/2;i++)
    str=str.replace("  "," ");
    System.out.println("String after removing whitespaces is :"+str);


Now you may have noticed that I have used a variable ln for storing the length of the string, and I have used the same for iteration of the loop ln/2 times.

The logic behind this is that since we are replacing double whitespace with a single whitespace, so the maximum iteration that we would need is obviously less than ln/2, and being a good programmer it is our sole responsibility to not only perform the given task but also do it in the most efficient way.

In the above program, I have initialized the string in the program itself.

You may ask the string from the user by inserting the simple piece of code which looks like this.


Scanner sc=new Scanner(;
String str;
System.out.println("Enter String");


Now when you compile the full Java code it will generate the following result, without any extra whitespaces.



String after removing whitespaces is: Java is the best programming language

Thanks for Reading.

Also, if there is something you didn’t understand do let me know in the comments section down below.

Have a nice day 🙂

Also, learn:

Leave a Reply

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