This post will discuss how to remove the last n characters from the end of a string in Java.

Since strings are immutable in Java, their length is fixed. That means we cannot make any change to the String instance. The only feasible solution is to create a new String object with the last n characters removed from the end of a string:

1. Using String.substring() method

The recommended approach is to use the substring() method provided by the String class. The idea is to take a substring from the beginning of the string and consider all the characters in it except the last n characters.

Download  Run Code

 
We should always ensure that a string is properly bounded, otherwise StringIndexOutOfBoundsException might be thrown. Here’s an exception-safe implementation:

Download  Run Code

2. Using StringUtils.removeEnd() method

We can also achieve this using the removeEnd method from the StringUtils class provided by the Apache Commons library. It removes a substring only if it is at the end of a source string, otherwise, it returns the source string. This is demonstrated below:

Download Code

That’s all about removing the last n characters from the end of a string in Java.