How to Remove Whitespaces from a String in Java
In this blog, we will learn how to remove whitespaces from a string in Java. This will be asked in the most of the interviews. This can be implemented in three different ways listed below:
- Convert String into character array and use for loop
- For loop with charAt() method
- Using replaceAll() method
Method 1:
Convert String into Character array and use for loop
In the below snippet we have done the following
- Created a string and assigned it with some value (includes whitespaces)
- Created a character array and converted the string into the array by using .toCharArray() method
- Created another empty string to store the output string
- By using char.length() method we’ve iterated for loop
- Used a If statement with a condition that to store only the values which are of not a period(whitespace) type.
public class RemoveWhitespacesString {
public static void main(String[] args) {
String str = "Java is a programming language";
char ch [] = str.toCharArray();
String str2 = "";
for(int i=0; i<ch.length; i++)
{
if(ch[i]!=' ')
{
str2 = str2 + ch[i];
}
}
System.out.println(str2);
}
}
Output: ------- Javaisaprogramminglanguage
Method 2:
Convert String into Character array and use for loop with CharAt() method
In the below snippet we have done the following
- Created a string and assigned it with some value (includes whitespaces)
- Created a character array and converted the string into the array by using .toCharArray() method
- Created another empty string to store the output string
- By using char.length() method we’ve iterated for loop
- Used a If statement with a condition that to store only the values which are of not a period(whitespace) type.
- Stored all the values into output string using charAt() method
public class RemoveWhitespacesString {
public static void main(String[] args) {
String str = "Java is a programming language";
char ch [] = str.toCharArray();
String str3="";
for(int i=0; i<ch.length; i++)
{
if(ch[i]!=' ')
{
str3 = str3 + str.charAt(i);
}
}
System.out.println(str3);
}
}
Output: ------- Javaisaprogramminglanguage
Method 3:
Using replaceAll() method:
In the below snippet, we have done the following:
- Created a string and assigned it with some value (includes whitespaces)
- Created another string to store the output value
- Using replaceAll() method with a regular expression which is a built-in method of string class we stored the value into the output string
public class RemoveWhitespacesString {
public static void main(String[] args) {
String str = "Java is a programming language";
String str4=str.replaceAll(" ", "");
System.out.println(str4);
}
}
Output: ------- Javaisaprogramminglanguage
Please watch the Youtube video for better understanding.







