How to remove spaces at beginning and at ending in Java


In java java.lang.String Class has a utility metod trim() which removes leading and trailing whitespaces from a String and returns a new String.
Following code shows you how to use trim() method to remove spaces at beginning and at ending from a String

public class TrimWhiteSpaces {
	
	public static void main(String[] args) {
		
		String stringWithSpaces = " foo boo     ";
		System.out.println("|" + stringWithSpaces + "|");
		
		// Trim spaces
		String stringWithoutSpaces = stringWithSpaces.trim();
		System.out.println("|" + stringWithoutSpaces + "|");
	}
	
}

Output:

| foo boo     |
|foo boo|