Home > Tutorial > Java String Trim Sample Code

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!      ";

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:

Posted by


I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot