java.lang.StringIndexOutOfBoundsException: String index out of range String.substring

The StringIndexOutOfBoundsException is thrown if you attempt to substring a string. If a invalid value is passed in begin and end index value, java.lang.IndexOutOfBoundsException will be thrown.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
 at java.lang.String.substring(String.java:1967)
 at com.yawintutor.StringSubstring.main(StringSubstring.java:8)

Root Cause

Using the substring method, a subset of the character sequence can be extracted from a string. The substring index must be any value from 0 to the length of a string. If the index exceeds the limit, StringIndexOutOfBoundsException is thrown in String substring method

How to reproduce this issue

If the value of the substring index is set above the limit of the string length, this exception will occur. The example below reproduces this problem.

package com.yawintutor;

public class StringSubstring {
 public static void main(String[] args) {
 String str = "Bangalore";
 String str2;

 str2 = str.substring(3, 1);

 System.out.println("Given  String : " + str);
 System.out.println("Output String : " + str2);
 }
}

Solution 1

The first parameter of the substring is begin index.

  • The value of the begin index should be zero or greater than zero.
  • The value of the begin index should not be more than the length of the string

Solution 2

The second parameter of the substring is end index. The end index is a optional value. If the end index is not passed, by default it is considered till end of the given string.

  • The value of the end index should be zero or greater than zero
  • The value of the end index should not be more than the length of the string
  • The value of the end index should be greater than or equals to the value of the start index.
package com.yawintutor;

public class StringSubstring {
 public static void main(String[] args) {
 String str = "Bangalore";
 String str2;

 str2 = str.substring(3, 8);

 System.out.println("Given  String : " + str);
 System.out.println("Output String : " + str2);
 }
}

Output

Given  String : Bangalore
Output String : galor

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *