Remove All Whitespace in Java

Published on 10 April 2026 (Updated: 10 April 2026)

Welcome to the Remove All Whitespace in Java page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

public class RemoveAllWhitespace {
    public static void main(String[] args) {
        if (args.length == 0 || args[0].isEmpty()) {
            showUsage();
        }

        System.out.println(removeAllWhitespace(args[0]));
    }

    private static void showUsage() {
        System.out.println("Usage: please provide a string");
        System.exit(1);
    }

    private static boolean isWhitespace(char c) {
        return switch (c) {
            case ' ', '\t', '\n', '\r' -> true;
            default -> false;
        };
    }

    private static String removeAllWhitespace(String input) {
        var result = new StringBuilder(input.length());

        for (char c : input.toCharArray()) {
            if (!isWhitespace(c)) {
                result.append(c);
            }
        }

        return result.toString();
    }
}

Remove All Whitespace in Java was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.