Get last 4 characters of String in Java

Learn how to get last 4 characters of a String or simply any number of last characters of a string in Java.

Get last 4 characters of String – Example

We may need to get last 4 characters when we are dealing with customer sesitive data such as phone numbers or SSN. In this case, we need to display only last 4 characters to mask the sensitive data.

To get substring having last 4 chars first check the length of string. If string length is greater than 4 then substring(int beginIndex) method. This method takes index position as method argument and return the complete string from that specified index.

If string length is less than 4, we can return the complete string as it is.

If data is in not in string form, use String.valueOf() method to convert it to String, first.

Feel free to modify below code if you need to get last n characters (other than 4). Simply replace '4' with desired number. For example, to get last two characters of a string, using method substring(input.length() - 2).

String input = "123456789";		//input string
String lastFourDigits = "";		//substring containing last 4 characters

if (input.length() > 4) 
{
    lastFourDigits = input.substring(input.length() - 4);
} 
else 
{
    lastFourDigits = input;
}

System.out.println(lastFourDigits);

Program output.

6789

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.