How to Remove the Last Character in a String in Java


Suppose we want to remove the last character from the string coffee to create the word coffe.

String str = "coffee"; // We want "coffe"

In Java, we can use the substring() function to obtain any substring of a string.

As explained in the docs, we have two ways of using this method:

substring(int beginIndex)
substring(int beginIndex, int endIndex)

If we supply two parameters, this method will return the substring from beginIndex (inclusive) to endIndex (exclusive).

str.substring(0, str.length()-1); // "coffe"

To avoid any index out of bounds errors, we can add a null and empty check before running this substring() function.

if (str != null && str.length() > 0) {
    str.substring(0, str.length()-1); // "coffe"
}