Skip to content

Java String Get First N Characters

Java String get first n characters example shows how to get first n characters from String in Java using the charAt method or substring method.

How to get the first n characters from the string in Java?

There are a couple of ways in which we can get first n characters from the string, one by one, or as a substring.

How to get first n characters as substring?

In order to get the first few characters from the string as a substring, we are going to use the String substring method.

This method returns the substring of the string starting from the startIndex till the endIndex. The startIndex parameter is inclusive while the endIndex is exclusive.

Here is the code example that shows how to get the first 4 characters from the string using the substring method.

Output

However, if the string length is less than the 4 characters, the above code will throw StringIndexOutOfBoundsException exception. In order to avoid that, we need to check the string length first before getting the substring.

Output

The statement “str.length() > num ? num : str.length()” checks if the string length is greater than the number of characters we want to extract. If it is, it returns the number of characters, otherwise, string length.

Instead of that, we can also use the min method of the Math class as shown below.

Output

How to get first n chars one by one?

To get the characters one by one, we are going to use the charAt method of the String class. It returns the character at the given index value. We can loop through the characters using the for loop as given below.

Output

The above code works fine as long as the given string length is greater than the number of characters we want to get from it. However, if the string length is less than the number of characters we want to get, it will throw StringIndexOutOfBoundsException exception as shown below.

Output

In order to avoid this exception, we should always check the string length as given below.

Output

If you want to learn more about the string in Java, please visit the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.