In this tutorial, we are going to shed light on how to remove the last character from a string in Java.

First, we will start by exploring different ways to do so in Java 7. Then, we are going to showcase how to accomplish the same objective using Java 8 or above methods.

Finally, we will explain how to use external libraries such as Apache Commons.

Remove the Last Character in Java 7

JDK 7 offers multiple methods and classes that we can use to remove a character from a string. Let’s take a close look at each option.

Using substring() Method

Typically, substring() provides the easiest and fastest way to delete the last char in Java.

As the name implies, this method returns a portion that is a substring of the given string. As a matter of fact, substring() accepts two parameters that denote the first index and the last one.

So, all we need to do to remove the last character is to pass 0 as the starting index and the length()-1 as the ending index.

Now, let’s see it in action:

    
        public static String usingSubstringMethod(String text) {
            if (text == null || text.length() == 0) {
                return text;
            }
            return text.substring(0, text.length() - 1);
        }
    

As we can see, the method is not null-safe, this is why we added the null-check control and the length condition.

Using replaceAll() with Regex

Alternatively, we can rely on regular expressions to delete the last character from a string.

All we need to do is find the right regex and use the replaceAll() method to match the string against it.

For example, in our case we can use ”.$” which matches the last char of a given string:

    
        public static String usingRegex(String text) {
            if (text == null || text.length() == 0) {
                return text;
            }
            
            return text.replaceAll(".$", "");
        }
    

Using StringBuffer.deleteCharAt() Method

Another solution would be using the StringBuffer class.

This class simply denotes a mutable sequence of characters. Unlike the String class, StringBuffer is thread-safe and modifiable.

Among the methods of this class, we find deleteCharAt(int index) that can be used to delete the char at the specified index.

Let’s see how we can use it to delete the character at the end of a particular string:

    
        public static String usingStringBufferClass(String text) {
            if (text == null || text.length() == 0) {
                return text;
            }
            
            StringBuffer strBuffer = new StringBuffer(text);
            return strBuffer.deleteCharAt(text.length() - 1)
                .toString();
        }
    

The position that holds the last character is text.length()-1. We used the toString() method to get the string from our StringBuffer object.

Please bear in mind that deleteCharAt(int index) throws StringIndexOutOfBoundsException if the specified index is negative or greater than the length of the string.

Using StringBuilder Class

Similarly, we can use StringBuilder to achieve the same purpose. The difference between StringBuffer and StringBuilder is that StringBuilder is not thread-safe.

StringBuilder offers also the deleteCharAt() method. However, we will use here another method called delete() to remove the last char.

Let’s illustrate the use of the StringBuilder.delete() method using a practical example:

    
        public static String usingStringBuilderClass(String text) {
            if (text == null || text.length() == 0) {
                return text;
            }

            StringBuffer strBuffer = new StringBuffer(text);
            return strBuffer.delete(text.length() - 1, text.length())
                .toString();
        }
    

As shown above, the delete() method removes the characters between the passed indexes. In our case, the removed char will be simply the last one.

Delete the last Char in Java 8 and Above

Now, that we know how to delete the last char using Java 7, let’s see how we can do the same thing using Java 8.

Using Optional Class

As we can see in the previous examples, the first thing we need to deal with before implementing the removal logic is making sure that our string is not null and not empty.

Well, the good news is that we don’t have to do this with the Optional Class. This class provides a concise and efficient way to handle the null-check.

So, without further ado, let’s see it in action:

    
        public static String usingOptionalClass(String text) {
            return Optional.ofNullable(text)
                .filter(str -> str.length() != 0)
                .map(str -> str.substring(0, str.length() - 1))
                .orElse(text);
        }  
    

Obviously, Optional offers a fancy way to remove the last char of a particular string in a null-safe manner.

Using Java 9 codePoints() Method

Java 9 upgrades the String class with a brand new handy method called codePoints().

Simply put, this method returns a stream of code point values from a string.

Now, let’s demonstrate the use of this new method with an example:

     
        public static String usingCodePointsMethod(String text) {
            return text.codePoints()
                .limit(text.length() - 1)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();
        }
    

As we can see, we used the limit(text.length()-1) method to tell the stream to ignore and delete the last character.

Apache Commons Lang3 Library

The Apache Commons Lang library provides the StringUtils class for string manipulation.

First, we need to add the Apache Commons dependency to our pom.xml.

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

StringUtils comes with two handy methods that we can use to delete the character at the end of a string.

So, let’s dig deep and explore each one.

Using StringUtils.chop() Method

StringUtils provides the chop() method, especially to remove the last character from a string.

This method accepts a String object as a parameter. The good thing about chop() is that it’s null-safe, so we don’t have to worry about null or empty strings.

     
        public static String usingStringUtilsChopMethod(String text) {
            return StringUtils.chop(text);
        }
    

Using StringUtils.substring() Method

StringUtils.substring() returns a substring from a given string in an exception-safe manner. Its internal implementation handles the null-check.

The method requires three parameters: the string, the first, and the last index:

     
        public static String usingStringUtilsSubstringMethod(String text) {
            int lastIndex = text != null ? text.length() - 1 : 0;
            return StringUtils.substring(text, 0, lastIndex);
        }
    

Conclusion

In summary, we have covered in-depth different ways to remove the last character from a string in Java.

We explored a couple of ways to achieve this using built-in Java 7 and Java8 methods. Along the way, we showcased how to accomplish the same thing using the Apache Commons Lang library.