This post will discuss how to remove the first n characters from a String in Java.

You cannot modify a string in Java since they are immutable. The only way to remove the first n characters from it is to create a new String object with the first n chars removed. There are several ways to do it:

1. Using Apache Commons library

A simple, concise, and elegant solution is to use the StringUtils class from Apache Commons Lang library whose removeStart() method removes a substring from the beginning of a source string, if present. You can use it as follows:

Download Code

2. Using String#substring() method

If you don’t prefer the Apache Commons library, you can use the String#substring() method to get a substring starting from the specific position in the string till its end.

Download  Run Code

 
If the specified index is negative or larger than the string’s length, IndexOutOfBoundsException will be thrown. You can easily handle it by placing a length check before invoking the substring() method.

Download  Run Code

That’s all about removing the first n characters from a String in Java.