Method to Get Last n Characters of a String in JAVA

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.

Next

Send Data to Server Using Google Volley in Android

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: