Removing the last character from a string in Java
In this tutorial, we are going to learn about how to remove the last character from a string in Java.
Removing the last character
To remove the last character from a string, we can use the built-in substring()
method by passing 0
as a first argument and string.length()-1
as the second argument in Java.
Here is an example, that removes the last character a
from the greet
string:
String greet = "helloa";
String result = greet.substring(0, greet.length()-1)
System.out.println(result);
Output:
hello
In the example above, we have passed 0, greet.length()-1
as arguments to the substring()
method. so it begins the extraction at index position 0
and extracts before the last character position of a string.
Note: The substring() method doesn’t mutates the original string, instead of it creates a new one with the extracted characters.