

#Java substring how to#
How to reproduce this exception using charAt() Exception in thread "main" : String index out of range: -1Īt (String.java:1967)Īt (StringSubstringCharAt.java:8) If the index value in the error message is negative value or positive value, the exception “String index out of range” is thrown using string.substring() method. The error message is shown as below. Exception in thread "main" : String index out of range: 1

If the index value in the error message is zero or positive value, the exception “String index out of range” is thrown using string.charAt() method. The error message is shown as below. If the index exceeds the limit, StringIndexOutOfBoundsException is thrown in String substring method The substring index must be any value from 0 to the length of a string. Using the substring method, a subset of the character sequence can be extracted from a string. Exception in thread "main" : String index out of range: 0Īt (String.java:658)Īt (StringSubstring.java:8) If the index exceeds the limit, substring method returns “String index out of range: 0” exception. The StringIndexOutOfBoundsException is thrown if you try to substring or find a character in a java string.Ī subset of the sequence of characters can be extracted from a string by using the Java substring() method. The substring index should be any value between 0 and the length of a string. If a invalid value is passed in begin and end index value, “: String index out of range” will be thrown.

Here, we see the exception “ : String index out of range: 0“. In Java, “ String index out of range” exception is thrown in java substring() & charAt() method.
