java.lang.IndexOutOfBoundsException: String index out of range: -1 at String.charAt

The String.charAt method in java returns the character at the given index in a string. If the index value should be in between 0 and the length of the string. If the index value is beyond the limit, java.lang.StringIndexOutOfBoundsException is thrown by the String method.

This exception is thrown by any String methods that checks the index of the String. For example, below methods throws java.lang.IndexOutOfBoundsException

  • String.charAt
  • String.codePointAt
  • String.codePointBefore
  • String.codePointCount
  • String.offsetByCodePoints
  • String.getChars
  • String.getBytes
  • String.substring
  • String.subSequence
  • String.valueOf
  • String constructor String(char[] value, int offset, int count)
  • String constructor String(int[] codePoints, int offset, int count)
  • String constructor String(byte[] bytes, int offset, int length, String charsetName) throws UnsupportedEncodingException
  • String constructor String(byte[] bytes, int offset, int length, Charset charset)
  • String constructor String(byte[] bytes, int offset, int length)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
	at java.lang.String.charAt(String.java:658)
	at com.yawintutor.StringCharAt.main(StringCharAt.java:8)

Root Cause

The above methods checks with a given index in the string. The index value must be in between 0 and the length of the String. If the index value is exceeds the range of the value then java.lang.IndexOutOfBoundsException will be thrown by any of the above methods.

Solution 1

Check the given index value of the String. It should follow the below condition

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

Solution 2

If the string method requires two index value like begin index and end index, both the index should follow the condition specified in the first solution. In additionally, it should follow the below condition

  • The end index should be equal or greater than the begin index

Example

package com.yawintutor;

public class StringCharAt {
	public static void main(String[] args) {
		String str = "Bangalore";
		char ch;

		ch = str.charAt(7);

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

Output

Given  String : Bangalore
Output Char   : r

Related Articles

Leave a Reply

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