Keywords: Java String Manipulation | substring Method | Boundary Condition Checking
Abstract: This article provides an in-depth exploration of various methods to safely extract the last three characters from a string in Java. It details the proper usage of the substring() method, including boundary condition handling and exception management. Alternative approaches using Apache Commons StringUtils.right() are also introduced, with comprehensive code examples demonstrating best practices across different scenarios. The discussion extends to performance considerations, memory management, and practical application recommendations.
Problem Context and Requirements Analysis
In Java programming practice, there is often a need to extract substrings from specific positions within strings. A common requirement is obtaining the last three characters, which is particularly useful in scenarios such as handling file extensions, data masking, and identifier truncation. Users initially attempted to use the getChars() method, but this approach requires pre-allocating a character array buffer, making it relatively complex and error-prone.
Core Solution: The substring Method
The Java String class provides a concise and efficient substring() method to address this issue. The basic syntax is: word.substring(word.length() - 3), which extracts from the specified index to the end of the string. When the string length is exactly 3, the original string is returned directly; when the length is greater than 3, the last three characters are returned.
Boundary Condition Handling
In practical applications, it is essential to consider cases where the string length is insufficient. Below is a complete implementation:
public String getLastThreeChars(String word) {
if (word == null) {
throw new IllegalArgumentException("Input string cannot be null");
}
if (word.length() == 3) {
return word;
} else if (word.length() > 3) {
return word.substring(word.length() - 3);
} else {
throw new IllegalArgumentException("word has fewer than 3 characters!");
}
}
Alternative Approach: Apache Commons Utility Library
For projects that have already incorporated Apache Commons Lang, the StringUtils.right() method can be used:
import org.apache.commons.lang3.StringUtils;
String input = "123456789";
String lastThreeChars = StringUtils.right(input, 3);
This method automatically handles null values and insufficient lengths, returning the specified number of rightmost characters, or the entire string if fewer characters are available.
Performance Analysis and Best Practices
The substring() method in Java 7 and later versions creates a new string object, with a time complexity of O(1). For scenarios involving frequent operations, it is advisable to pre-check the string length to avoid unnecessary exception throwing. When dealing with user input or external data, null checks and length validation are indispensable steps.
Application Scenario Extensions
This technique can be widely applied in: file extension extraction, displaying the last few digits of phone numbers, ID number masking, log message truncation, and more. By parameterizing the character count, it can be easily extended into a universal method for obtaining any number of trailing characters.