In this post, I am going to share a simple method that will help you to get last n (1, 2, 3 4, …) characters from a String in Java. This method is very simple as it just takes String and integer count as a parameter and returns another string containing the last specified number of characters. The Java function is the following.
Method to Get Last n Characters of a String in Java
public static String getLastNCharsOfString(String str, int n) {
String lastnChars = str;
if (lastnChars.length() > n) {
lastnChars = lastnChars.substring(lastnChars.length() - n, lastnChars.length());
}
return lastnChars;
}
Input
getLastNCharsOfString("Hello world", 3);
Return Value (Output)
"rld"
How it Works
This method takes a String and an integer as a parameter. Then it first checks the count of string to avoid index out of bound exception. If the integer n value is greater than the total length of the String, it uses subString method to get the last specified character from the string.
Enjoy 🙂
If you have any questions feel free to ask in the comments section below.