This post will discuss how to get the last n characters from a string in Java.

1. Using Apache Commons Lang

To get the rightmost n characters of a string, you can use the right() method offered by the StringUtils class from Apache Commons Lang. The advantage of using this method is that it doesn’t throw StringIndexOutOfBoundsException or NullPointerException when n characters are not available, or the string is null.

Download Code

2. Using String.substring() method

To remove the n characters from the end of a string, you can make a call to the substring() method with the last n indices excluded. Here’s a utility method demonstrating this:

Download  Run Code

 
Here’s an alternative version that performs length check within the substring() method:

Download  Run Code

That’s all about getting the last n characters from a string in Java.