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 !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.