- Class StringBuilder
- Java StringBuilder remove last character example (StringBuffer)
- How to remove the last character from the StringBuilder or StringBuffer?
- 1. Using the deleteCharAt method
- 2. Using the setLength method
- What is the best way to remove the last character from StringBuilder or StringBuffer?
- About the author
- Java Stringbuilder delete last character [2 ways]
- Java StringBuilder delete the last character
- 1. Using StringBuilder class deleteCharAt() method
- 2. Using StringBuilder class setLength() method
- Java — Remove last character from string builder in java
- 1. Remove last char
- 2. Safe way to remove last char
- 3. Remove last char if it is equal to specific character
- References
- Class StringBuilder
Class StringBuilder
A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.
In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .
Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
Java StringBuilder remove last character example (StringBuffer)
This example shows how to remove the last character from the StringBuilder or StringBuffer object using the deleteCharAt and setLength methods. It also shows the best way to delete the last character.
How to remove the last character from the StringBuilder or StringBuffer?
1. Using the deleteCharAt method
We can use the deleteCharAt method to remove the character at any given index from the StringBuilder or StringBuffer object.
This method removes a character located at the specified index. To remove the last character, we need to pass StringBuilder length – 1 as the index to the deleteCharAt method, as shown in the below example.
Before calling the deleteCharAt method always check that the length of the StringBuilder object is greater than 0 to avoid the StringIndexOutOfBoundsException exception.
2. Using the setLength method
We can also use the setLength method of the StringBuilder class to remove the last character from it.
This method sets the length of the character sequence stored in the StringBuilder or StringBuffer object. To remove the last character, we need to pass StringBuilder length – 1 to the setLength method as given below.
What is the best way to remove the last character from StringBuilder or StringBuffer?
Let’s have a look at the source code for both of these methods. Here is the source code of the deleteCharAt method which is directly taken from the OpenJDK 8 AbstractStringBuilder class.
And here is the source code of the setLength method.
By looking at the source code above, we can see that the deleteCharAt method uses the arraycopy method of the System class to remove the specified character from the StringBuilder object. Whereas, the setLength method simply sets the internal buffer count to the specified new length if the current length is greater than or equal to the new length (that is the case when we want to remove a character).
To copy an array is a costly operation as compared to setting the value of an internal variable in terms of performance. Hence, the setLength method should be used to remove the last character over deleteCharAt method due to performance reasons.
Please let me know your views in the comments section below.
About the author
I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.
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
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)
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
Java — Remove last character from string builder in java
Wallace
Remove last character from StringBuilder in Java is simple. StringBuilder has build in method deleteCharAt(). As a parameter we pass current length of our StringBuilder.
StringBuilder builder = new StringBuilder(); builder.deleteCharAt( builder.length() - 1 );
1. Remove last char
2. Safe way to remove last char
In order to saftly remove last character from StringBuilder in java, we need to check the length of StringBuilder. In case we won’t do it and the StringBuilder will be longer we get:
Example with safe way of how to remove last char:
public class Example < public static void main(String[] args) < StringBuilder builder = new StringBuilder(); builder.append("1234"); System.out.println( builder.toString() ); // 1234 removeLastChar(builder); System.out.println( builder.toString() ); // 123 >public static void removeLastChar(StringBuilder builder) < if (builder.length() >0) < builder.deleteCharAt( builder.length() - 1 ); >> >
This method allow us to avoid the below exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:824) at java.lang.StringBuilder.deleteCharAt(StringBuilder.java:253)
3. Remove last char if it is equal to specific character
This example extends the previous one. We just add one more condition. We need to check if the last letter of StringBuilder is equals to the letter we want to find.
public class Example < public static void main(String[] args) < StringBuilder builder = new StringBuilder(); builder.append("1234a"); System.out.println( builder.toString() ); // 1234a removeLastChar(builder, 'a'); System.out.println( builder.toString() ); // 1234 >public static void removeLastChar(StringBuilder builder, char letter) < if (builder.length() >0 && builder.charAt(builder.length() - 1) == letter) < builder.deleteCharAt(builder.length() - 1); >> >
References
Class StringBuilder
A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.
In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .
Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.