1. Introduction

In this post, we will write a Java program to remove all whitespaces from a given String. Whitespaces are any character that is either a space, a tab, or a newline character.

2. Program Steps

1. Define a class named RemoveWhitespaces.

2. Inside this class, define the main method.

3. Inside the main method, define a String that contains whitespaces.

4. Utilize the replaceAll() method of the String class to remove all whitespaces from the String.

5. Print the original String and the modified String.

3. Code Program

public class RemoveWhitespaces { // Step 1: Define a class named RemoveWhitespaces

    public static void main(String[] args) { // Step 2: Define the main method

        // Step 3: Define a String that contains whitespaces
        String strWithWhitespaces = "Java    Programming    is    Fun";

        // Step 4: Use replaceAll() method to remove all whitespaces from the String
        String strWithoutWhitespaces = strWithWhitespaces.replaceAll("\\s+", "");

        // Step 5: Print the original and modified String
        System.out.println("Original String: " + strWithWhitespaces);
        System.out.println("String without Whitespaces: " + strWithoutWhitespaces);
    }
}

Output:

Original String: Java    Programming    is    Fun
String without Whitespaces: JavaProgrammingisFun

4. Step By Step Explanation

Step 1: A class named RemoveWhitespaces is defined.

Step 2: The main method is defined inside the RemoveWhitespaces class.

Step 3: A String named strWithWhitespaces is defined, which contains whitespaces.

Step 4: The replaceAll() method of the String class is used with the regex "\\s+" to replace all whitespaces in the String with an empty String, effectively removing them.

Step 5: The original String and the String without whitespaces are printed to the console.