Flash cards
Review the key moves
What is the main idea behind Java How To - Remove Whitespace from a String?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ text = " Java ";Put the learning moves in the order that makes the concept easiest to apply.
Remove Whitespace from a String
There are two common ways to remove whitespace in Java: using trim() and using replaceAll() .
Remove Whitespace at the Beginning and End
The trim() method only removes whitespace from the start and end of the string.
Example
String text = " Java ";
String trimmed = text.trim();
System.out.println(trimmed); // "Java"Explanation: trim() is useful when you only want to clean up leading and trailing spaces, but it will not touch spaces inside the string.
Remove All Whitespace
If you want to remove all spaces, tabs, and newlines in a string, use replaceAll() with a regular expression.
Example
String text = " Java \t is \n fun ";
String noSpaces = text.replaceAll("\\s+", "");
System.out.println(noSpaces); // "Javaisfun"Explanation: The regular expression \\s+ matches any whitespace character (spaces, tabs, newlines). Replacing them with an empty string removes all whitespace from the text.