When java.lang.StringIndexOutOfBoundsException occurs in java

What is hierarchy of java.lang.StringIndexOutOfBoundsException?

-java.lang.Object
-java.lang.Throwable
 -java.lang.Exception
  -java.lang.RuntimeException
   -java.lang.IndexOutOfBoundsException
    -java.lang.StringIndexOutOfBoundsException



StringIndexOutOfBoundsException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?

java.lang.StringIndexOutOfBoundsException is a RuntimeExceptions in java.


What is StringIndexOutOfBoundsException in java?

StringIndexOutOfBoundsException is thrown when an string is accessed with an illegal index.

The index accessed may be >

  • Negative or
  • equal to the size of string
  • greater than the size of array.



Scenarios where StringIndexOutOfBoundsException may be thrown in java>

  1. If index accessed is Negative, StringIndexOutOfBoundsException is thrown
  2. If index accessed is equal to the size of array, StringIndexOutOfBoundsException is thrown
  3. If index accessed is greater than the size of array, StringIndexOutOfBoundsException is thrown

public class StringIndexOutOfBoundsExceptionExample {
public static void main(String args[]) {
     String str= "abcd";
    
     //If index accessed is Negative, StringIndexOutOfBoundsException is thrown
     //System.out.println(str.charAt(-1));
     System.out.println(str.charAt(0)); //a
     System.out.println(str.charAt(1)); //b
     System.out.println(str.charAt(2)); //c
     System.out.println(str.charAt(3)); //d
    
     //If index accessed is equal to the size of array, StringIndexOutOfBoundsException is thrown
     //System.out.println(str.charAt(4));
    
     //If index accessed is greater than the size of array, StringIndexOutOfBoundsException is thrown
     //System.out.println(str.charAt(5));
}
}


If we uncomment any of the above comment line StringIndexOutOfBoundsException will be thrown >

System.out.println(str.charAt(-1));
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(Unknown Source)
at  StringIndexOutOfBoundsExceptionExample.main(StringIndexOutOfBoundsExceptionExample.java:7)



System.out.println(str.charAt(4));
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at  StringIndexOutOfBoundsExceptionExample.main(StringIndexOutOfBoundsExceptionExample.java:14)



System.out.println(str.charAt(5));
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at  StringIndexOutOfBoundsExceptionExample.main(StringIndexOutOfBoundsExceptionExample.java:17)

eEdit
Must read for you :