Languages
[Edit]
EN

Java - get last 3 characters of string

0 points
Created by:
Dirask Admin - Marwin
1460

In this article, we would like to show you how to get the last 3 characters of a string in Java.

Quick solution: 

String text = "This is your text";
String lastThreeCharacters = text.substring(text.length() - 3);

System.out.println( lastThreeCharacters ); // ext

Practical example

Below example shows how to use .substring() method to get the last 3 characters of the text string.

public class StringExample {

    static String getLastCharacters(String text, int numberCount) {
        if (text.length() == numberCount) {
            return text;
        } else if (text.length() > numberCount) {
            return text.substring(text.length() - numberCount);
        } else {
            throw new IllegalArgumentException("Your text is less than " + numberCount + " 3 characters long!");
        }
    }

    public static void main(String[] args) {
        System.out.println( getLastCharacters("12345", 3) ); // 345
        System.out.println( getLastCharacters( "1234", 3) ); // 234
        System.out.println( getLastCharacters(  "123", 3) ); // 123
        System.out.println( getLastCharacters(   "12", 3) ); // IllegalArgumentException
    }
}

Output: 

345
234
123
Exception in thread "main" java.lang.IllegalArgumentException: Your text is less than 3 characters long!

Java - String (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join