Remove last character from string

The opposite of deleting the first character in a string this example will show how to delete the last character in a java string.

Straight up Java

Using core java we will check if the phrase is null and if the length is greater than 1. If the length is less than then we know the String is empty. Then using substring we will start at position 0 as a beginning index. For the ending index we want the total length of the phrase minus 1 which will discard the last value. You can subtract any value as long as you modify the prior if check.

@Test
public void delete_last_char_java() {

    String phrase = "level up lunch";

    String rephrase = null;
    if (phrase != null && phrase.length() > 1) {
        rephrase = phrase.substring(0, phrase.length() - 1);
    }

    assertEquals("level up lunc", rephrase);
}

Apache Commons

Using apache commons StringUtils we will call the chop method, which will encapsulate the logic above, will remove the last character from a String.

@Test
public void delete_last_char_apache() {
    
    String phrase = "level up lunch";
    
    String rephrase = StringUtils.chop(phrase);
    
    assertEquals("level up lunc", rephrase);
}