</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to remove all whitespace characters from a string.

Answer

Remove Whitespace from a String

Java
public class RemoveWhiteSpacesInaString {
    public static void main(String[] args) {
        String str = " Core Java selenium automation oops programming ";

        String strWithoutSpace = str.replaceAll("\\s", "");

        System.out.println("Original: '" + str + "'");
        System.out.println("Without spaces: '" + strWithoutSpace + "'");
    }
}

Output

CODE
Original: ' Core Java selenium automation oops programming '
Without spaces: 'CoreJavaseleniomautomationoopsprogramming'

Different Whitespace Removal Options

Java
String str = "  Core  Java  Selenium  Testing  ";

// 1. Remove ALL whitespace (spaces, tabs, newlines)
System.out.println(str.replaceAll("\\s", ""));
// → CoreJavaSeleniumTesting

// 2. Remove only leading and trailing whitespace
System.out.println(str.trim());
// → "Core  Java  Selenium  Testing"

// 3. Remove only leading whitespace
System.out.println(str.replaceAll("^\\s+", ""));
// → "Core  Java  Selenium  Testing  "

// 4. Remove only trailing whitespace
System.out.println(str.replaceAll("\\s+$", ""));
// → "  Core  Java  Selenium  Testing"

// 5. Collapse multiple spaces into single space
System.out.println(str.trim().replaceAll("\\s+", " "));
// → "Core Java Selenium Testing"

// 6. Java 11+ strip() — handles Unicode whitespace too
System.out.println(str.strip());         // trim + Unicode whitespace
System.out.println(str.stripLeading());  // leading only
System.out.println(str.stripTrailing()); // trailing only

\s vs \s+ Difference

Java
String str = "Hello   World";

str.replaceAll("\\s", "");   // removes each space individually → "HelloWorld"
str.replaceAll("\\s+", " "); // replaces groups of spaces with single space → "Hello World"

Automation Testing Relevance

Java
// Handle unpredictable whitespace in element text
String elementText = driver.findElement(By.css(".title")).getText();
String cleanText   = elementText.trim().replaceAll("\\s+", " ");  // normalize spaces

// Compare text ignoring whitespace differences
String expected = "Confirm Order";
String actual   = driver.findElement(By.id("btn")).getText().trim();
assertEquals(actual, expected, "Button text mismatch");

// Remove whitespace when checking phone number format
String phone   = driver.findElement(By.id("phone")).getText();
String digits  = phone.replaceAll("\\s", "");  // "(555) 123 4567" → "5551234567"

Follow AutomateQA