Java String trim() Method Examples

Filed Under: Java
Java String Trim

Java String trim() method is used to remove leading and trailing whitespaces from a string. This method treats any character whose Unicode codepoint is less than or equal to ‘U+0020’ as a whitespace character.

  • If the string contains only whitespaces, an empty string is returned.
  • If there are no leading and trailing whitespaces in the string, the reference to the same string is returned.
  • Java String is immutable, so the original string object value remains unchanged.

Java String trim() Example

Let’s look at a simple example of String trim() method.

package com.journaldev.examples;

public class StringTrim {

	public static void main(String[] args) {
		String str = "  abc  def \t\t ";
		String str1 = str.trim();


***  abc  def 		 ***
***abc  def***

I am appending a few non-whitespace characters while printing the string so that the difference is clearly visible in the output.

Let’s look at another example using the JShell interpreter.

jshell> String str = "  abc  def \t\t ";
str ==> "  abc  def \t\t "

jshell> str.trim();
$2 ==> "abc  def"

String trim() vs strip() Method

Java 11 added many new methods in the string class. One of them is the strip() method that does the same job as the trim() method.

However, the strip() method uses Character.isWhitespace() method to check if the character is a whitespace. This method uses Unicode code points whereas trim() method identifies any character having codepoint value less than or equal to ‘U+0020’ as a whitespace character.

The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.


Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors