How to Remove Space from String in Java

Java String provides several inbuilt methods to remove space from String in Java like trim() method, which removes whitespace from beginning and end.

 

While using the trim() method, the key thing to remember is that trim() returns a different String object than the older one because String is immutable in Java.

On the other hand, if you want to remove all white spaces from string i.e. white space from beginning, end and between words then you can use replaceAll() method of String and pass regular expression \s to find and replace all white spaces including a tab with the empty string ” “.

 

Program to Remove Space from String in Java

Here is Java program example to remove all white spaces from any String in Java. We have used trim() method to delete white space from beginning as well ad from the end.

OutPut : 

String before removing White space :
This String contains White Space at beginning and end and middle
length of String before removing white space 72 :
String after removing white space from beginning and end
This String contains White Space at beginning and end and middle
length of String after removing white space from beginning and end 64 : String with white space between words: ABC DEF GHI
String after removing white space between words and everywhere: ABCDEFGHI

 

That’s all on How to remove all white space from String in Java, including white space from beginning, end and middle of String. Just to note you can not remove white spaces only from middle of String or between words, because when you use replaceAll(“\\s”,””) it also removes white spaces from beginning and end of String.

1 Comment
  1. Informative 8:59 AM / September 16, 2016 - Reply

    Thanks to share…. your explanation is so impressive and easy… Thanks you again

Leave a Reply