java.lang.String trim()

Description :

This java tutorial shows how to use the trim() method of String class of java.lang package. This method returns a new String which is a exact value of the original String stripped with leading and trailing spaces.

Method Syntax :

public String trim()

Parameter Input :

DataType Parameter Description
N/A N/A N/A

Method Returns :

The trim() method of String class returns a new String object. The method returned value is a copy of the original String with leading and trailing spaces omitted.

Compatibility Version :

Requires Java 1.4 and up

Exception :

None

Discussion :

The trim() method of String class is a way to normalize the string input which sometimes have a trailing and leading white spaces. These white spaces messes with our logic and display of these information. I have encountered many instances where my code logic fails because of white spaces on a String.

By invoking the trim() method, it returns a new String object. It doesn’t replace the value of String object. Thus if we want to have access to the new String object, we just need to assign it to a new variable or reassign it to the old String.

Java Code Example :

This example source code demonstrates the use of trim() method of String class to remove the leading and trailing spaces.

package com.javatutorialhq.java.tutorial.string;

/*
 * This example source code demonstrates the use of trim() method
 */
public class StringTrimExample {

	public static void main(String[] args) {
		// String declaration with trailing and leading space
		String inputValue = "  this is an example java code ";
		// removing the white spaces
		String newValue = inputValue.trim();
		System.out.println(newValue);
	}

}

Sample Output :

Running the trim() method example source code of String class will give you the following output

string trim method example

string trim method example

Exception Scenario :

N/A

Suggested Reading List :

References :