Remove Spaces from a String in Java
Problem
Removing spaces means dropping every space character from a string while keeping every other character in place.
Given a string, remove every space character from it.
Java Program
public class RemoveSpaces {
public static void main(String[] args) {
String str = "Java Programming Language";
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
if (c != ' ') result.append(c); // skip the space character entirely
}
System.out.println(result.toString());
}
}Output
Core Logic
A single pass through the string, appending every character except a space, builds the space-free result.
- 1A for-each loop visits each character of the string in turn.
- 2
if (c != ' ')checks whether the current character is anything other than a space. - 3Characters that pass the check are appended to a
StringBuilder; spaces are simply skipped. - 4The final
StringBuilderholds every original character except the spaces.
"Java Programming Language", the two spaces between words are skipped, producing "JavaProgrammingLanguage".Key Point: This checks only the literal space character — tabs or newlines would still be appended to the result, unlike a check based on Character.isWhitespace().
Why: Each character is visited once and the result buffer grows to hold every non-space character, which can be up to n.
Key Concepts
Approach 2: Using replace()
public class RemoveSpacesBuiltin {
public static void main(String[] args) {
String str = "Java Programming Language";
// replace() swaps every space for an empty string, which deletes it
System.out.println(str.replace(" ", ""));
}
}
Output
Core Logic
In real code, there's no reason to loop manually — replace() already removes every matching character in one call.
- 1
str.replace(" ", "")takes the space character as the target and an empty string as the replacement. - 2Every occurrence of a space is replaced with nothing, which is the same as deleting it.
- 3The result is a brand-new string with no spaces left.
"Java Programming Language".replace(" ", "") returns "JavaProgrammingLanguage" in a single call.Key Point: This is the version to actually use — the manual loop exists only to show what replace() is conceptually doing under the hood.
Why: replace() still has to scan the whole string and build a new one without the matched character, but that work happens inside the JDK instead of your own loop.
Key Concepts
Approach 3: Java 8
import java.util.stream.Collectors;
public class RemoveSpacesStream {
public static void main(String[] args) {
String str = "Java Programming Language";
// Keeps every character except spaces, then joins them back into a String
String result = str.chars()
.filter(c -> c != ' ')
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
System.out.println(result);
}
}
Output
Core Logic
The same skip-the-spaces logic can filter a stream of character codes down to the non-space ones, then join what's left.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.filter(c -> c != ' ')keeps every code except the space character. - 3
.mapToObj(c -> String.valueOf((char) c))converts each surviving code back into a one-characterString. - 4
.collect(Collectors.joining())concatenates them all back into a single result string.
"Java Programming Language" drops both spaces, and joining what's left reassembles "JavaProgrammingLanguage".Key Point: The filter condition is the exact same check the loop version uses — streams just change how it's applied across the string.
Why: The stream still visits every character once, and Collectors.joining() builds a result string holding every non-space character.