Write a program to trim any leading or trailing whitespace from a given string


The code snippet you provided is an example of trimming leading and trailing white spaces from a string in Java. It uses the trim() method of the String class to remove any white spaces at the beginning and end of the string.

In the code, the string " Computer " (with leading and trailing spaces) is assigned to the variable str. The trim() method is then used to remove the white spaces, and the result is stored in the variable new_str. Finally, the original string and the trimmed string are printed to the console using System.out.println() statements.

Source Code

public class Trim_WhiteSpace
{
	public static void main(String[] args)
	{
		String str = "	Computer	";
		String new_str = str.trim();
		System.out.println("Given String :" + str);
		System.out.println("After Trim White Space in String :" + new_str);
	}
}

Output

Given String :  Computer
After Trim White Space in String :Computer

Example Programs