Skip to content

Java String remove last character example

Java String remove last character example shows how to remove the last character from String in Java. The example also shows how to remove the last 2, 3, and n characters from String.

How to remove the last character from String in Java?

The last character of a string can be removed using the substring method of the String class.

This method returns a string that is a substring of the original String.

Important Note: Remember, the startIndex is inclusive while the endIndex is exclusive. That is, the substring starts at startIndex and goes up to endIndex – 1 (not till the endIndex).

You can remove the last character of String using below given approaches.

1) Using the substring method

Take substring from the original String from 0 to string length – 1 index to remove the last character from the String as given below.

Output

It is necessary to check for null, otherwise call thesubstring method on a null string will throw NullPointerException exception. If the string is empty and the substring method is called, it will throw ArrayIndexOutOfBoundException exception.

2) Using the Apache Commons library

If you are using the Apache Commons library, you can use the removeEnd method of the StringUtils class to remove the last character from the String as given below.

Output

How to check the last character before removing it?

Sometimes it is a good idea to check the last character before removing it from the String. You can use the endsWith method of the String class to do that.

For example, if you want to make sure that the last character of the string is indeed a comma, you can do so as given below.

Output

Using Apache Commons

If you are using the removeEnd method of the StringUtils class, there is no need to check the last character. That is because the  removeEnd method removes the last character only if the string ends with it. If the last character does not match, it returns the original String back as given below.

Output

Since “Hello, world,” string does not end with the “d”, it is not removed from the string and original string is returned back.

How to remove the last 2 characters from the String?

Use the substring method and specify 0 as the start index and string length – 2 as the end index to remove the last 2 characters from the String. Make sure that string’s length is at least 2, otherwise, the substring method will throw ArrayIndexOutOfBoundException exception.

Output

How to remove the last n characters from the String?

Same as above, take a substring from 0 to string length – n to remove the last n characters from the string. Make sure the string is at least n characters in length.

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.