Learn how to get the first 4 characters of a String or simply any number of the first characters of a string in Java.
1. Using Plain Java
To get a substring having the first 4 chars first check the length of the string. If the string length is greater than 4 then use substring(int beginIndex, int lastIndex) method. This method takes the start and last index positions to return the substring within those indices.
If the string length is less than 4, we can return the complete string as it is.
String input = "123456789"; //input string
String firstFourChars = ""; //substring containing first 4 characters
if (input.length() > 4)
{
firstFourChars = input.substring(0, 4);
} else {
firstFourChars = input;
}
System.out.println(firstFourChars);
If data is in not in string form, first use String.valueOf() method to convert it to String.
If you wish to get the first N characters, replace ‘4’ in the above java program with the desired number of characters. For example, to get the first 2 characters we can change the method call to input.substring(0, 2).
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.left() 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.left(input, 4);
Happy Learning !!