How to get the last character of a string in Java
In this tutorial, we are going to learn about how to get the last character of a string in Java.
Consider, we have the following string.
String str = "google";
Now, we want to get the last character e
from the above string.
Getting the last character
To access the last character of a string in Java, we can use the substring()
method by passing string.length()-1
as an argument.
Here is an example that gets the last character e
from the following string:
String str = "google";
System.out.println( str.substring(str.length()-1));
Output:
"e"
Similarly, you can also get the last two characters of a string like this:
String str = "google";
System.out.println( str.substring(str.length()-2));
Note: The extraction starts at str.length()-2
and ends upto last character index.