Java Program to Remove All Whitespaces From a String

You are currently viewing Java Program to Remove All Whitespaces From a String

In this article, You are going to know the concept of “Java Program to Remove All Whitespaces From a String”.

White spaces are nothing but blank spaces between two strings. We can use the str.replaceAll() function to remove all white spaces from a string here. Okay, Let’s move on to this article.

Java Program to Remove All Whitespaces From a String

Below, We can perform the task using this example program.

public class removeWhiteSpace {    
    public static void main(String[] args) {    
            
        String str1="Hello friends! Welcome to Codingdiksha";    
            
        //Removes the white spaces using regex    
        str1 = str1.replaceAll("\\s+", "");    
            
        System.out.println("String after removing all the white spaces : " + str1);    
    }    
}  

Source Code Explanation

Initially, We have to create the remove white space() class to start this program. Secondly, We need to declare the respective variable to store the input string. Thirdly, We will compile the program using the public static void main() function.

After compiling this program, The str.replaceAll(“\\s+”, “”) function will remove the all-white spaces from a string. Finally, The removed white spaces output will display on the screen using the system.out.printIn() function.

Read Also : Java Program to Replace Space with Underscore

Note

You can also remove all white spaces from a string using some other languages like PHP Program to Remove All White Spaces From String and C++ Program to Remove All White Spaces from String. please click on the link to learn about it.

Output of Java Program to Remove All Whitespaces from a String

Below, You can see the reference output.

String after removing all the white spaces : Hellofriends!WelcometoCodingdiksha

Final Words

I hope this article helps you to Remove All White Spaces from String in Java Program. If you face any issues please let me know via the comment section. Share this article with other Java program developers via social networks. Thank You!

Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.

Leave a Reply