Java How To -Remove Whitespace from a String
Remove Whitespace from a String
There are two common ways to remove whitespace in Java: usingtrim() and usingreplaceAll().
Remove Whitespace at the Beginning and End
Thetrim() 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 removeall spaces, tabs, and newlines in a string, usereplaceAll() 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.

