Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

How to remove white spaces from String

In this post, we are removing leading and trailing white spaces from a string in Java. Leading and trailing spaces are attached to the starting and end of the string. For example, a string "Studytonight" can have leading spaces like " Studytonight" and trailing spaces "Studytonight ".

To remove white spaces Java String class provides strip(), stripLeading() and stripTrailing() methods that are added in Java 11 version.

The strip() method is used to remove all leading and trailing white spaces of the string. It does not take any argument but returns a string to the caller.

The stripLeading() method is used to remove leading white spaces from the string. If we want to remove only leading spaces from the string then you can use this method and for removing only trailing white spaces you can use stripTrailing() method.

Time for an Example: Java 11

Let's create an example to remove white spaces from the tring. Here, we are using strip() method to remoe all the leading and trailing white space from the string.

public class Main {
	public static void main(String[] args){
		String str = "   Studytonight";
		System.out.println(str);
		System.out.println("hello"+str);
		// remove whitespace from String
		String newStr = str.strip();
		System.out.println(newStr);
		System.out.println("hello"+newStr);
	}
}


Studytonight
hello Studytonight
Studytonight
helloStudytonight

Example: Remove by using stripLeading() Method

Let's create another example to remove white spaces from a string. Here, we are using stripLeading() method that returns a string after removing all the leading white spaces.

public class Main {
	public static void main(String[] args){
		String str = "   Studytonight";
		System.out.println(str);
		System.out.println("hello"+str);
		// remove whitespace from String
		String newStr = str.stripLeading();
		System.out.println(newStr);
		System.out.println("hello"+newStr);
	}
}


Studytonight
hello Studytonight
Studytonight
helloStudytonight

Example: Remove by using stripTrailing() Method

Let's create one more example to remove white space from the string. Here, we are using the stripTrailing() method to get a string after removing all the trailing spaces. See the example below.

public class Main {
	public static void main(String[] args){
		String str = "   Studytonight  ";
		System.out.println(str);
		System.out.println("hello"+str+".com");
		// remove whitespace from String
		String newStr = str.stripTrailing();
		System.out.println(newStr);
		System.out.println("hello"+newStr+".com");
	}
}


Studytonight
hello Studytonight .com
Studytonight
hello Studytonight.com