What is StringUtils.chop() in Java?

chop is a static method of the StringUtils class that is used to remove the last character in the given string. If the last characters are \r\n, then two characters will be removed.

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added 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>

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

The StringUtils class can be imported as follows:

import org.apache.commons.lang3.StringUtils;

Syntax

public static String chop(String str)

Parameters

  • String str: the string from which to remove the final character

Return value

The function returns string with the last character removed.

The functions returns null if the input string is null.

Code

In the code below, we test the chop function on different inputs. If the input string ends with \r\n, then both the characters will be removed. Otherwise, only the last character will be removed.

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args)
{
System.out.println(StringUtils.chop(null));
System.out.println("\"" + StringUtils.chop("hello \n educative \r\n") + "\"");
System.out.println(StringUtils.chop("hello educative!"));
}
}

The output of the below code when executed is as follows:

null
"hello 
 educative "
hello educative

Free Resources