StringIndexOutOfBoundsException
KW.java
class KW
{
    public static void main(String args[])
    {
        String s="Hello, World!";
        System.out.println("Length: "+s.length());
        System.out.println("0th Character: "+s.charAt(0));
        System.out.println("14th Character: "+s.charAt(14));
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Length: 13 0th Character: H Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14 kodingwindow@kw:~$
Java program to handle the StringIndexOutOfBoundsException
KW.java
class KW
{
    public static void main(String args[])
    {
        String s="Hello, World!";
        System.out.println("Length: "+s.length());
        System.out.println("0th Character: "+s.charAt(0));
        try
        {
            System.out.println("14th Character: "+s.charAt(14));
        }
        catch(StringIndexOutOfBoundsException e)
        {
            System.out.println("Requested character not found");
        }
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Length: 13 0th Character: H Requested character not found kodingwindow@kw:~$
Advertisement