Get Last 4 Chars of a String in Java

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

1. Using Plain Java

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

To get a substring having the last 4 chars first check the length of the string. Suppose the string length is greater than 4 then use the substring(int beginIndex) method that returns the complete string from that specified beginIndex.

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

String input = "123456789";
String lastFourChars = "";  

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

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

2. Using Apache Common’s StringUtils

Include the latest version of Apache commons lang from the Maven repo.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

The StringUtils.right() method gets the rightmost n characters of a String. If n characters are not available, or the String is null, the String will be returned without an exception. An empty String is returned if the argument is negative.

String input = "123456789";
String lastFourChars = StringUtils.right(input, 4); 

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.

Our Blogs

REST API Tutorial