How to remove all white spaces from a String in Java?

Given a String with white spaces, the task is to remove all white spaces from a string using Java built-in methods.

Examples:

Input: str = "       Geeks     for    Geeks   "            
Output: GeeksforGeeks

Input:  str = "    A  Computer  Science   Portal"
Output: AComputerSciencePortal

To remove all white spaces from String, use replaceAll() method of String class with two arguments, i.e.

replaceAll("\\s", "");
where \\s is a single space in unicode

Program:

filter_none

edit
close

play_arrow

link
brightness_4
code

class BlankSpace {
    public static void main(String[] args)
    {
        String str = "      Geeks     for    Geeks        ";
       
        // Call the replaceAll() method
        str = str.replaceAll("\\s", "");
       
        System.out.println(str);
    }
}

chevron_right


Output:

GeeksforGeeks


My Personal Notes arrow_drop_up

सर्वशक्तिशाली इकलौता

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.