Java Stringbuilder delete last character [2 ways]

In this post, I will be sharing how to delete the last character from StringBuilder. In other words, how to remove the last character from the StringBuilder object. There are two ways to achieve our goal:

1. Using deleteCharAt() method of StringBuilder class

2. Using setLength() method of StringBuilder class

Read Also: StringBuilder append to the start/front in Java

Let's dive deep into the topic:

Java StringBuilder delete the last character

1. Using StringBuilder class deleteCharAt() method


According to Oracle docs, we can easily delete the character at any index of the StringBuilder object using the deleteCharAt() method.

The syntax of the deleteCharAt() method is given below:

 public StringBuilder deleteCharAt(int index)

You can find the example of the deleteCharAt() method below:

 public class StringBuilderDeleteCharAtExample {
    public static void main(String args[]) {
      // Initialize StringBuilder Object
      StringBuilder sb = new StringBuilder("Alive is Awesome");
      if(!sb.isEmpty()) {
          sb.deleteCharAt(sb.length() - 1);
      }
      System.out.println("Removed last character: " + sb);
    }
}


Output:
Removed last character: Alive is Awesom


2. Using StringBuilder class setLength() method


We can easily remove the last character from the StringBuilder object using the setLength() method. The syntax of the setLength() method is given below:

 public void setLength(int newLength)


The above method sets the length of the character sequence. To remove the last character from the StringBuilder object, we need to pass sb.length()-1 as an argument to the setLength() method as shown below in the example:

 public class StringBuilderSetLengthExample {
    public static void main(String args[]) {
      // Initializing StringBuilder Object
      StringBuilder sb2 = new StringBuilder("Be in Present");
      // Checking if StringBuilder object is not empty
      if(!sb2.isEmpty()) {
          sb2.setLength(sb2.length() - 1);
      }
      System.out.println("Removed last character using setLength() method: " + sb2);
    }
}


Output:
Removed last character using setLength() method: Be in presen


That's all for today. Please mention in the comments if you have any questions related to how to delete the last character from StringBuilder in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry