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);
    lastFourDigits = input;


Program output.


Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.