To remove last character from a string in Java, we can use built-in method such as substring(), deleteCharAt(), chop(), etc. Since String is a sequence of characters, it is easy to pick the last element with the help of the index value. Let's see the examples:
We will use all these methods one by one in our examples to remove the last char from a string.
Here, we used the substring() method of the String class to get a substring by specifying the start and end index. This method takes two arguments, the first is the start index, and the second is the last index of the substring. See the code example.
/*
* Code example to remove last char from the String in Java
*/
public class JExercise {
public static void main(String[] args){
// Take a String
String str = "Hello";
System.out.println(str);
// Remove last char from the String
str = str.substring(0, str.length() - 1);
System.out.println(str);
}
}
Output:
Hello
Hell
The deleteCharAt() method belongs to the StringBuilder class, so we can use this method after converting the string object to the StringBuilder object. This method takes a single argument, so we passed only the second last index of the String to remove the last char. After removing the last char, we can convert it back to a String object by using the toString() method. See the code below.
/*
* Code example to remove last char from the String in Java
*/
public class JExercise {
public static void main(String[] args){
// Take a String
String str = "Hello";
System.out.println(str);
// Remove last char from the String
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(str.length() - 1);
System.out.println(sb);
// Convert StringBuilder back to String
str = sb.toString();
System.out.println(str);
}
}
Output:
Hello
Hell
Hell
If you are working with the apache library, you can use the chop() method of StringUtils class that returns a String object after removing the last character. We don't need to pass an index of the String in this case. It is one of the easy solutions. See the code below.
import org.apache.commons.lang3.StringUtils;
/*
* Code example to remove last char from the String in Java
*/
public class JExercise {
public static void main(String[] args){
// Take a String
String str = "Hello";
System.out.println(str);
// Remove last char from the String
String str2 = StringUtils.chop(str);
System.out.println(str2);
}
}
Output:
Hello
Hell