In Java, “String index out of range” exception is thrown in java substring() & charAt() method. Here, we see the exception “java.lang.StringIndexOutOfBoundsException: String index out of range: 0“. If a invalid value is passed in begin and end index value, “java.lang.StringIndexOutOfBoundsException: String index out of range” will be thrown. The StringIndexOutOfBoundsException is thrown if you try to substring or find a character in a java string.
A 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 the index exceeds the limit, substring method returns “String index out of range: 0” exception.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
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
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.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at com.yawintutor.StringSubstring.main(StringSubstring.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" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at com.yawintutor.StringSubstringCharAt.main(StringSubstringCharAt.java:8)
How to reproduce this exception using charAt()
The charAt() method is used to read a character in the java string. The parameter index is used to identify the location of the character in the string. If the index location is not available in the string, the error “java.lang.StringIndexOutOfBoundsException: String index out of range: 0” is thrown
package com.yawintutor;
public class StringSubstringCharAt {
public static void main(String[] args) {
String str = "";
char ch;
ch = str.charAt(0);
System.out.println("Given String : " + str);
System.out.println("Output Charcter : " + ch);
}
}
Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at com.yawintutor.StringSubstring.main(StringSubstring.java:8)
How to reproduce this exception with Substring
If the value of the substring index is set above the limit of the string length, this exception “java.lang.StringIndexOutOfBoundsException: String index out of range: -1” will occur. The example below reproduces this exception.
package com.yawintutor;
public class StringSubstringCharAt {
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);
}
}
Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.substring(String.java:1967)
at com.yawintutor.StringSubstringCharAt.main(StringSubstringCharAt.java:8)
Solution 1
The java string contain an empty value. If the string is null, then NullPointerException will be thrown. As the java program thrown with index 0, “java.lang.StringIndexOutOfBoundsException: String index out of range: 0”, the java string may be an empty string.
Check the string or character sequence value. Make sure the string contains value or add the empty string validation in the code.
package com.yawintutor;
public class StringSubstringCharAt {
public static void main(String[] args) {
String str = "";
char ch='';
if(str!=null && str.length()!=0) {
ch = str.charAt(0);
}
System.out.println("Given String : " + str);
System.out.println("Output Charcter : " + ch);
}
}
Output
Given String :
Output Charcter :
Solution 2
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 3
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 StringSubstringCharAt {
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
Содержание
- Библиотека примеров приложений Java
- 1.6. Обработка исключений
- Немного теории
- Описание примера
- Исключение ArrayIndexOutOfBoundsException
- Исключение ArithmeticException
- Исключение ArrayStoreException
- Исключение ClassCastException
- Исключение NegativeArraySizeException
- Исключение NullPointerException
- Исключение StringIndexOutOfBoundsException
- How to handle StringIndexOutOfBoundsException in Java?
- Example
- Output
- Index in an array
- Index in a Sting
- StringIndexOutOfBoundsException
- Example
- Run time exception
- Handling StringIndexOutOfBoundsException exception
- Fix Java.Lang.StringIndexOutOfBoundsException: String Index Out of Range
- Fix the java.lang.StringIndexOutOfBoundsException: String index out of range Error
- java.lang.StringIndexOutOfBoundsException – How to solve StringIndexOutOfBoundsException
- The Structure of StringIndexOutOfBoundsException
- Constructors
- Библиотека примеров приложений Java
- 1.6. Обработка исключений
- Немного теории
- Описание примера
- Исключение ArrayIndexOutOfBoundsException
- Исключение ArithmeticException
- Исключение ArrayStoreException
- Исключение ClassCastException
- Исключение NegativeArraySizeException
- Исключение NullPointerException
- Исключение StringIndexOutOfBoundsException
Библиотека примеров приложений Java
1.6. Обработка исключений
В примере демонстрируются приемы обработки исключений нескольких типов, возникающих в приложениях Java.
Немного теории
Механизм исключений, предусмотренный в языке программирования Java, упрощает обработку ошибок. Вместо того чтобы проверять значение, возвращаемое функциями и методами, вы можете использовать для обнаружения и обработки ошибок структурные операторы, такие как try и catch.
Методы стандартных библиотек классов Java возбуждают исключения при возникновении ошибочных ситуаций. Заключив «ненадежный» с точки зрения возникновения ошибок код в блок try, вы можете перехватить и обработать исключения в блоке catch.
Заметим, что исключения возникают и в таких распространенных ситуациях, как выход за пределы массива или строки в процессе индексации, деление на нуль, попытка использования ссылки со значением null, недопустимое преобразование классов и так далее. С помощью исключений все подобные ошибки нетрудно обнаружить и обработать во время выполнения приложения.
Описание примера
В нашем примере мы покажем типичные ситуации, в которых возникают исключения.
Исключение ArrayIndexOutOfBoundsException
Это исключение возникает, когда программа пытается адресовать элементы за пределами массива.
В нашем примере мы используем исключение ArrayIndexOutOfBoundsException для завершения цикла обработки массива при достижении его границы:
Если не предусмотреть обработку исключения, программа завершится аварийно. Как только значение переменной i достигнет пяти, будет вызван системный обработчик исключений.
Наш обработчик, заданный в теле оператора catch, выводит название исключения на консоль, а затем прерывает выполнение цикла при помощи оператора break. Таким образом, программа продолжает свою работу «штатным» образом несмотря на предпринятую попытку выхода за границы массива.
Сообщение об исключении, отображенное приведенным выше фрагментом кода на консоли, выглядит следующим образом:
Исключение ArithmeticException
Ниже мы выполняем попытку деления числа 5 на нуль:
В результате такой попытки возникает исключение ArithmeticException и наша программа выводит на консоль соответствующее сообщение, показанное ниже:
Исключение ArrayStoreException
Если попытаться записать в ячейку массива ссылку на объект неправильного типа, возникнет исключение ArrayStoreException.
Ниже мы создаем массив класса Object, предназначенный для хранения строк класса String:
При попытке записать в первый элемент этого массива ссылку на объект класса Character возникает исключение:
Исключение ClassCastException
В языке программирования Java вы не можете выполнять явное преобразование типов произвольным образом. Если выполнить такое преобразование для классов, не связанных «узами» наследования, или другим недопустимым способом, возникнет исключение ClassCastException.
Ниже мы создаем ссылку на объект класса Character, а затем пытаемся выполнить преобразование этой ссылки к типу Byte:
В результате возникает исключение:
Исключение NegativeArraySizeException
Это исключение возникает при попытке создать массив отрицательного размера.
В приведенном ниже фрагменте кода мы создаем массив с размером -5:
При этом возникает исключение NegativeArraySizeException:
Исключение NullPointerException
Если попытаться использовать в программе ссылку, содержащую значение null, возникнет исключение NullPointerException.
Ниже мы создаем ссылку на массив nNulArray, записываем в нее значение null, а затем пытаемся определить размер массива, вызывая для этого метод length:
В результате возникает исключение:
Исключение StringIndexOutOfBoundsException
В Java есть методы, позволяющие работать с отдельными символами строк класса String. Например, метод charAt позволяет извлечь символ, расположенный в заданной позиции. Если указать позицию, лежащую за границей строки, возникнет исключение StringIndexOutOfBoundsException.
Ниже мы предпринимаем попытку извлечения десятого символа из строки, в которой имеется только три символа:
При этом возникает исключение, а на экране появляется сообщение следующего вида:
Источник
How to handle StringIndexOutOfBoundsException in Java?
Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.
You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).
Example
Output
Index in an array
An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.
The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.
Index in a Sting
Since the string stores an array of characters, just like arrays the position of each character is represented by an index (starting from 0). For example, if we have created a String as −
The characters in it are positioned as −
StringIndexOutOfBoundsException
If you try to access the character of a String at the index which is greater than its length a StringIndexOutOfBoundsException is thrown.
Example
The String class in Java provides various methods to manipulate Strings. You can find the character at a particular index using the charAt() method of this class.
This method accepts an integer value specifying the index of theStringand returns the character in the String at the specified index.
In the following Java program, we are creating a String of length 17 and trying to print the element at the index 40.
Run time exception
Since we are accessing the element at the index greater than its length StringIndexOutOfBoundsException is thrown.
Handling StringIndexOutOfBoundsException exception
Just like other exceptions you can handle this exception by wrapping the code that is prone to it within try catch. In the catch block catch the exception of type IndexOutOfBoundsException or, StringIndexOutOfBoundsException.
Источник
Fix Java.Lang.StringIndexOutOfBoundsException: String Index Out of Range
This tutorial demonstrates the Exception in thread «main» java.lang.StringIndexOutOfBoundsException: String index out of range: 0 error in Java.
Fix the java.lang.StringIndexOutOfBoundsException: String index out of range Error
The StringIndexOutofBoundsException is an unchecked exception that occurs when accessing the character of a string for which the index is either negative or more than the String length. This exception is also thrown when we use the charAt() method, which is trying to access a character that is not in the String.
Because StringIndexOutofBoundsException is an unchecked exception, it doesn’t need to add to throws of a method or constructor; we can handle it using the try-catch block. Here are the specific scenarios where this exception can occur:
- When using String.charAt(int index) , which will return a character at a given String index. If the index is negative or greater than the String’s length, it will throw the StringIndexOutofBoundsException.
- When using String.valueOf(char[] data, int offset, int count) which returns a string with given arguments. It will throw the StringIndexOutofBoundsException when any index is negative or offset + count is greater than the size of the array.
- When using CharSequence.subSequence(int beginIndex, int endIndex) which returns a character sequence. It will throw the StringIndexOutofBoundsException when beginIndex is greater than endIndex, or endIndex is greater than the length of the String.
- When using String.substring(int beginIndex) , which returns a substring from the given String. It will throw the StringIndexOutofBoundsException when beginIndex is negative or greater than the length of the String.
- When using String.substring(int beginIndex, int endIndex) , which returns a sub-string between a specific range. It will throw the StringIndexOutofBoundsException when any index is negative, or endIndex is greater than the length of String of beginIndex is greater than endIndex .
Let’s try an example for StringIndexOutofBoundsException . See example:
The code above will throw StringIndexOutofBoundsException because there is no character at index 11. See output:
The StringIndexOutOfBoundsException can be handled using try-catch blocks. See solution:
Источник
java.lang.StringIndexOutOfBoundsException – How to solve StringIndexOutOfBoundsException
Posted by: Sotirios-Efstathios Maneas in exceptions September 25th, 2014 0 Views
In this tutorial we will discuss about the java.lang.StringIndexOutOfBoundsException in Java. This exception is thrown by the methods of the String class, in order to indicate that an index is either negative, or greater than the size of the string itself. Moreover, some methods of the String class thrown this exception, when the specified index is equal to the size of the string.
The java.lang.StringIndexOutOfBoundsException class extends the IndexOutOfBoundsException class, which is used to indicate that an index to either an array, a string, or a vector, is out of range.
Furthermore, the IndexOutOfBoundsException extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.
Finally, the java.lang.StringIndexOutOfBoundsException exists since the 1.0 version of Java.
The Structure of StringIndexOutOfBoundsException
Constructors
- StringIndexOutOfBoundsException()
Creates an instance of the java.lang.StringIndexOutOfBoundsException class, setting null as its message.
- StringIndexOutOfBoundsException(int index)
Creates an instance of the java.lang.StringIndexOutOfBoundsException class with the specified argument indicating the illegal index.
- StringIndexOutOfBoundsException(String s)
Источник
Библиотека примеров приложений Java
1.6. Обработка исключений
В примере демонстрируются приемы обработки исключений нескольких типов, возникающих в приложениях Java.
Немного теории
Механизм исключений, предусмотренный в языке программирования Java, упрощает обработку ошибок. Вместо того чтобы проверять значение, возвращаемое функциями и методами, вы можете использовать для обнаружения и обработки ошибок структурные операторы, такие как try и catch.
Методы стандартных библиотек классов Java возбуждают исключения при возникновении ошибочных ситуаций. Заключив «ненадежный» с точки зрения возникновения ошибок код в блок try, вы можете перехватить и обработать исключения в блоке catch.
Заметим, что исключения возникают и в таких распространенных ситуациях, как выход за пределы массива или строки в процессе индексации, деление на нуль, попытка использования ссылки со значением null, недопустимое преобразование классов и так далее. С помощью исключений все подобные ошибки нетрудно обнаружить и обработать во время выполнения приложения.
Описание примера
В нашем примере мы покажем типичные ситуации, в которых возникают исключения.
Исключение ArrayIndexOutOfBoundsException
Это исключение возникает, когда программа пытается адресовать элементы за пределами массива.
В нашем примере мы используем исключение ArrayIndexOutOfBoundsException для завершения цикла обработки массива при достижении его границы:
Если не предусмотреть обработку исключения, программа завершится аварийно. Как только значение переменной i достигнет пяти, будет вызван системный обработчик исключений.
Наш обработчик, заданный в теле оператора catch, выводит название исключения на консоль, а затем прерывает выполнение цикла при помощи оператора break. Таким образом, программа продолжает свою работу «штатным» образом несмотря на предпринятую попытку выхода за границы массива.
Сообщение об исключении, отображенное приведенным выше фрагментом кода на консоли, выглядит следующим образом:
Исключение ArithmeticException
Ниже мы выполняем попытку деления числа 5 на нуль:
В результате такой попытки возникает исключение ArithmeticException и наша программа выводит на консоль соответствующее сообщение, показанное ниже:
Исключение ArrayStoreException
Если попытаться записать в ячейку массива ссылку на объект неправильного типа, возникнет исключение ArrayStoreException.
Ниже мы создаем массив класса Object, предназначенный для хранения строк класса String:
При попытке записать в первый элемент этого массива ссылку на объект класса Character возникает исключение:
Исключение ClassCastException
В языке программирования Java вы не можете выполнять явное преобразование типов произвольным образом. Если выполнить такое преобразование для классов, не связанных «узами» наследования, или другим недопустимым способом, возникнет исключение ClassCastException.
Ниже мы создаем ссылку на объект класса Character, а затем пытаемся выполнить преобразование этой ссылки к типу Byte:
В результате возникает исключение:
Исключение NegativeArraySizeException
Это исключение возникает при попытке создать массив отрицательного размера.
В приведенном ниже фрагменте кода мы создаем массив с размером -5:
При этом возникает исключение NegativeArraySizeException:
Исключение NullPointerException
Если попытаться использовать в программе ссылку, содержащую значение null, возникнет исключение NullPointerException.
Ниже мы создаем ссылку на массив nNulArray, записываем в нее значение null, а затем пытаемся определить размер массива, вызывая для этого метод length:
В результате возникает исключение:
Исключение StringIndexOutOfBoundsException
В Java есть методы, позволяющие работать с отдельными символами строк класса String. Например, метод charAt позволяет извлечь символ, расположенный в заданной позиции. Если указать позицию, лежащую за границей строки, возникнет исключение StringIndexOutOfBoundsException.
Ниже мы предпринимаем попытку извлечения десятого символа из строки, в которой имеется только три символа:
При этом возникает исключение, а на экране появляется сообщение следующего вида:
Источник
- HowTo
- Java Howtos
- Fix …

This tutorial demonstrates the Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
error in Java.
Fix the java.lang.StringIndexOutOfBoundsException: String index out of range
Error
The StringIndexOutofBoundsException
is an unchecked exception that occurs when accessing the character of a string for which the index is either negative or more than the String length. This exception is also thrown when we use the charAt()
method, which is trying to access a character that is not in the String.
Because StringIndexOutofBoundsException
is an unchecked exception, it doesn’t need to add to throws of a method or constructor; we can handle it using the try-catch
block. Here are the specific scenarios where this exception can occur:
- When using
String.charAt(int index)
, which will return a character at a given String index. If the index is negative or greater than the String’s length, it will throw theStringIndexOutofBoundsException.
- When using
String.valueOf(char[] data, int offset, int count)
which returns a string with given arguments. It will throw theStringIndexOutofBoundsException
when any index is negative oroffset + count
is greater than the size of the array. - When using
CharSequence.subSequence(int beginIndex, int endIndex)
which returns a character sequence. It will throw theStringIndexOutofBoundsException
whenbeginIndex
is greater thanendIndex,
orendIndex
is greater than the length of the String. - When using
String.substring(int beginIndex)
, which returns a substring from the given String. It will throw theStringIndexOutofBoundsException
whenbeginIndex
is negative or greater than the length of the String. - When using
String.substring(int beginIndex, int endIndex)
, which returns a sub-string between a specific range. It will throw theStringIndexOutofBoundsException
when any index is negative, orendIndex
is greater than the length of String ofbeginIndex
is greater thanendIndex
.
Let’s try an example for StringIndexOutofBoundsException
. See example:
package delftstack;
public class Example {
public static void main(String[] arg) {
String DemoStr = "delftstack";
System.out.println(DemoStr.charAt(11));
}
}
The code above will throw StringIndexOutofBoundsException
because there is no character at index 11. See output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:1512)
at delftstack.Example.main(Example.java:7)
The StringIndexOutOfBoundsException
can be handled using try-catch
blocks. See solution:
package delftstack;
public class Example {
public static void main(String[] arg) {
String DemoStr = "delftstack";
try {
System.out.println(DemoStr.charAt(11));
} catch(StringIndexOutOfBoundsException e) {
System.out.println("Please insert a index under String length: " + DemoStr.length());
}
}
}
Now the output for the above code is:
Please insert a index under String length: 10
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn
Facebook
Related Article — Java Error
The java.lang.StringIndexOutOfBoundsException is RuntimeException or Checked Exception which is thrown by the methods of String class during index operations which indicate accessing index is either negative or greater than size of string itself.
java.lang.StringIndexOutOfBoundException is subclass of the IndexOutOfBoundException class which is used to indicate that accessing index to either an Array, Vector or String, is out of Range.
String Class Methods where StringIndexOutOfBoundsException happen:
String object index range is between 0
to String.length() -1
if object access beyond this range lower or greater will throw StringIndexOutOfBoundsException .
- public char charAt(int index);
- public String substring(beginIndex);
- public String subString(beginIndex,endIndex);
- public CharSequence subSequence(beginIndex,endIndex);
- public static String valueOf(char[] data, int offset, int count)
Example : Below example is for print all possible SubString for String FacingIssuesOnIT will throw StringIndexOutOfBoundException. on run time because index conditions are not properly handled.
package example; public class StringIndexOutOfBounExceptionExample { public static void main(String[] args) { String str = "FacingIssueOnIT"; System.out.println("*********All Substring of FacingIssuesonIT"); for (int i = 0; i <= str.length(); i++) { for (int j = i + 1; j <= str.length(); j++) { System.out.println(str.substring(i, j - i)); } } } }
Output :
*********All Substring of FacingIssuesonIT F Fa Fac Faci Facin Facing FacingI FacingIs FacingIss FacingIssu FacingIssue FacingIssueO FacingIssueOn FacingIssueOnI a ac aci acin acing acingI acingIs acingIss acingIssu acingIssue acingIssueO acingIssueOn Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at example.StringIndexOutOfBounExceptionExample.main(StringIndexOutOfBounExceptionExample.java:10)
Issues with above Example :
Actually, your right edge of your substring function may be lower than the left one. For example, when i=(size-1)
and j=size
, you are going to compute substring(size-1, 1)
. This is the cause of you error.
Modified Example:
When you compare with above example loop condition are change SubString above range selection is modified.
package example; public class StringIndexOutOfBounExceptionExample { public static void main(String[] args) { String str = "FacingIssueOnIT"; System.out.println("*********All Substring of FacingIssuesOnIT"); for (int i = 0; i <=str.length()-1; i++) { for (int j = i+1 ; j <= str.length(); j++) { //System.out.println("i="+i+",j="+ j); System.out.println(str.substring(i, j)); } } } }
Output:
*********All Substring of FacingIssuesOnIT F Fa Fac Faci Facin Facing FacingI FacingIs FacingIss FacingIssu FacingIssue FacingIssueO FacingIssueOn FacingIssueOnI FacingIssueOnIT a ac aci acin acing acingI acingIs acingIss acingIssu acingIssue acingIssueO acingIssueOn acingIssueOnI acingIssueOnIT c ci cin cing cingI cingIs cingIss cingIssu cingIssue cingIssueO cingIssueOn cingIssueOnI cingIssueOnIT i in ing ingI ingIs ingIss ingIssu ingIssue ingIssueO ingIssueOn ingIssueOnI ingIssueOnIT n ng ngI ngIs ngIss ngIssu ngIssue ngIssueO ngIssueOn ngIssueOnI ngIssueOnIT g gI gIs gIss gIssu gIssue gIssueO gIssueOn gIssueOnI gIssueOnIT I Is Iss Issu Issue IssueO IssueOn IssueOnI IssueOnIT s ss ssu ssue ssueO ssueOn ssueOnI ssueOnIT s su sue sueO sueOn sueOnI sueOnIT u ue ueO ueOn ueOnI ueOnIT e eO eOn eOnI eOnIT O On OnI OnIT n nI nIT I IT T
How to avoid StringIndexOutOfBoundException?
- Debug program throughly after printing index values.
- During operation check index value range between 0 to String.length()-1.