Java String Trim Sample Code

The String.trim() method will return a copy of the string referenced with all the leading and trailing whitespace removed.

Method Arguments Return
trim() None String


Java String Trim Leading & Trailing Whitespace

The trim() method will only remove all leading and trailing whitespace. It will not remove whitespace in the middle of your String object. So whitespace is defined as one ore more spaces in a row that are either at the beginning or ending of your String.

 
String jcdString = "       Java Code Depot Rocks!      ";
jcdString.trim()


Java String Trim Source Code

package com.jcd.java.tutorials;

public class JavaStringTrim 
{

	public static void main(String[] args) 
	{
		
		//Trim off both leading and trailing whitespace
		String jcdString1 = "       Java Code Depot Rocks!      ";
		System.out.println("\nBefore Trim: "+jcdString1);
		System.out.println("After Trim: "+jcdString1.trim());
		
		//Trim all leading/trailing whitespace and modify variable
		String jcdString2 = "      JavaCodeDepot.com      ";
		jcdString2 = jcdString2.trim();
		System.out.println("\njcdString2 Contents: "+jcdString2);

	}	

}


Java String Trim Source Code Output


Before Trim:        Java Code Depot Rocks!      
After Trim: Java Code Depot Rocks!

jcdString2 Contents: JavaCodeDepot.com



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *