In this article, I will be sharing different ways to remove the first and last character from String in java. There are 2 ways to achieve the result.
1. Using substring() method
2. Using deleteCharAt(int index)
Let's dive deep into the topic.
Read Also: Difference between String, StringBuilder, and StringBuffer
1. Using substring(int beginIndex, int endIndex) methodsubstring() method is present in the String class. String class provides two overloaded substring methods but we will use the below method to remove first and the last character from the given String.
substring(int beginIndex, int endIndex)
The above method will create the substring starting from the beginIndex and extends to the character at index endIndex-1. In simple words, substring() will include beginIndex and extends till the end excluding the endIndex.
Since String is immutable i.e once created can not be changed or modified, substring() method will return a new String without first and last character. The length of the new substring() will be endIndex - beginIndex.
2. Using deleteCharAt(int index)deleteCharAt(int index) method is present in StringBuilder/StringBuffer class. We need to first convert String to StringBuilder/StringBuffer object.
Removing the first character from String using deleteCharAt(int index) method:
Removing the last character from String using deleteCharAt(int index) method:
Removing both the first and last character from String using deleteCharAt(int index) method:
That's all for today regarding removing the first and last character from String in Java. If you know any other way to solve this problem or have any questions please mention in comments.