Last Updated:

How to remove the last character in a string [ Java ]

Method 1: String.substring()

 

The String.substring() method returns a substring of the string to look for with the specified length. The String.length() method returns the length of the string. By combining these two methods, we can return a string without the last character:

 

public static String removeLastChar(String s) {
return (s == null || s. length() == 0) ? null : (s.substring(0, s. length() - 1));
}

This method is null-safe, that is, if you pass null as an argument, it will work correctly and return null as well.

Method 2: StringUtils.chop()

Here we will use the Apache Commons library. First, connect it to your project:

 

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

Then use the StringUtils.chop() method:

 

public static String removeLastChar2(String s) {
return StringUtils. chop(s);
}

This method is also null-safe.

Source code

 

public class RemoveLastCharSubstring {
 
public static void main(String[] args) {
System. out. println(removeLastChar("abcdef"));
System. out. println(removeLastChar2("abcdef"));
}
 
public static String removeLastChar(String s) {
return (s == null || s. length() == 0) ? null : (s.substring(0, s. length() - 1));
}
 
public static String removeLastChar2(String s) {
return StringUtils. chop(s);
}
}

Conclusion

 

In this tutorial we figured out how to remove the last character from a string in Java.