What is StringUtils.trim() in Java?

Overview

trim() is a staticthe methods in Java that can be called without creating an object of the class. method of the StringUtils class which removes the control characters from both ends of the input string. This method internally uses the trim method of the String class.

How to import StringUtils

The definition of StringUtils can be found in the Apache Commons Lang package which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the StringUtils class as follows:


import org.apache.commons.lang3.StringUtils;

Syntax

The syntax of the trim() method is as follows:


public static String trim(final String str)

Parameters

The trim() method takes the following parameter:

  • final String str: The string to trim.

Return value

This method returns trimmed string.

The method returns null if the input string is null.

Code

The code below shows how you can use the trim() method in Java:

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
// Example 1
String s = "\n hellO-EDUcative \r\r\n";
System.out.printf("The output of StringUtils.trim() for the string - '%s' is '%s'", s, StringUtils.trim(s));
System.out.println();
// Example 2
s = "";
System.out.printf("The output of StringUtils.trim() for the string - '%s' is '%s'", s, StringUtils.trim(s));
System.out.println();
// Example 3
s = null;
System.out.printf("The output of StringUtils.trim() for the string - '%s' is '%s'", s, StringUtils.trim(s));
System.out.println();
}
}

Output

The output of the code will be as follows:


The output of StringUtils.trim() for the string - '
  hellO-EDUcative 
' is 'hellO-EDUcative'
The output of StringUtils.trim() for the string - '' is ''
The output of StringUtils.trim() for the string - 'null' is 'null'

Explanation

Example 1

  • string = " hellO-EDUcative "

The method returns hellO-EDUcative after removing the newline, carriage return and space characters from the input string.

Example 2

  • string = ""

The method returns `` as the input string is empty.

Example 3

  • string = null

The method returns null as the input string is null.

Free Resources

Attributions:
  1. undefined by undefined