This post will discuss how to get the first n characters of a String in Java, where n is a non-negative integer.

1. Using substring() method

To get the first n characters of a String, we can pass the starting index as 0 and ending index as n to the substring() method. Note that the substring() method returns IndexOutOfBoundsException if the ending index is larger than the length of the String. This can be handled using the ternary operator, as demonstrated below:

Download  Run Code

 
Instead of the ternary operator, we can also pass the minimum of string’s length and n as ending index in the substring() method.

Download  Run Code

2. Using Apache Commons Lang

Apache Commons Lang library StringUtils class offers several utility methods for null-safe substring extractions. To get the first n characters of a String, we can use the overload version of the substring() method, which returns a substring from a specified start position to a specified end position. Note that there is no need to explicitly handle the exception if n is more than the string’s length.

Download Code

 
The StringUtils class also has the left() method specifically for extracting the leftmost n characters of a String. If the string is null or n characters are not available, it returns the original String without any exception.

Download Code

3. Using Guava

Alternatively, we can use Guava’s Ascii.truncate() method to truncate the given string to the specific length.

Download Code

4. Using String.format() method

Finally, we can simply format the string using the String.format() method, which takes width indicating the minimum number of characters to be written to the output.

Download  Run Code

That’s all about getting first n characters of a String in Java.