Exception thrown java lang stringindexoutofboundsexception

java.lang.StringIndexOutOfBoundsException – How to solve StringIndexOutOfBoundsException

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

Creates an instance of the java.lang.StringIndexOutOfBoundsException class, setting null as its message.

Creates an instance of the java.lang.StringIndexOutOfBoundsException class with the specified argument indicating the illegal index.

Creates an instance of the java.lang.StringIndexOutOfBoundsException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The StringIndexOutOfBoundsException in Java

The following methods throw an java.lang.StringIndexOutOfBoundsException when the specified arguments are invalid:

This method returns the string representation of the specified sub-array argument. It throws an java.lang.StringIndexOutOfBoundsException if any index is negative, or if offset + count is larger than the size of the specified array.

Important: Notice that all constructor methods in the String that contain an array in their argument list, throw an java.lang.StringIndexOutOfBoundsException when the specified offset and count are invalid.

String’s charAt method

StringCharAtExample.java:

public class StringCharAtExample < public static void main(String[] args) < String str = "Java Code Geeks!"; System.out.println("Length: " + str.length()); //The following statement throws an exception, because //the request index is invalid. char ch = str.charAt(50); >>

In this example we define a sample string and then, print its length. Then, we try to retrieve the character at a specific index, but the specified index is much larger than the length of the string itself and thus, an java.lang.StringIndexOutOfBoundsException is thrown.

A sample execution is shown below:

Length: 16 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 50 at java.lang.String.charAt(String.java:646) at main.java.StringCharAtExample.main(StringCharAtExample.java:10)

String’s subSequence method

StringSubSequenceExample.java:

public class StringSubSequenceExample < public static void main(String[] args) < String str = "Java Code Geeks!"; System.out.println("Length: " + str.length()); //The following statement throws an exception, because //the request index is invalid. CharSequence seq = str.subSequence(10, 20); >>

In this example we define a sample string and then, print its length. Then, we try to create a CharSequence , starting from the 10th index and ending at the 20th index of the initial string. However, the length of the initial string is smaller than the requested end index and thus, an java.lang.StringIndexOutOfBoundsException is thrown.

Читайте также:  Php создать документ doc

A sample execution is shown below:

Length: 16 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20 at java.lang.String.substring(String.java:1950) at java.lang.String.subSequence(String.java:1990) at main.java.StringSubSequenceExample.main(StringSubSequenceExample.java:10)

String’s subString method

StringSubstringExample.java:

public class StringSubstringExample < public static void main(String[] args) < String str = "Java Code Geeks"; //The following statement throws an exception, because //the request index is invalid. String subStr = str.substring(20); >>

In this example we define a sample string and then, we try to create a new string that starts from the 20th index of the initial string. However, the length of the initial string is smaller than the requested end index and thus, an java.lang.StringIndexOutOfBoundsException is thrown.

A sample execution is shown below:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -5 at java.lang.String.substring(String.java:1918) at main.java.StringSubstringExample.main(StringSubstringExample.java:9)

StringSubstringExample_v2.java:

public class StringSubstringExample_v2 < public static void main(String[] args) < String str = "Java Code Geeks"; //The following statement throws an exception, because //the request index is invalid. String subStr = str.substring(10, 20); >>

In this example we define a sample string and then, we try to create a new string that starts from the 10th index and ends at the 20th index of the initial string. However, the length of the initial string is smaller than the requested end index and thus, an java.lang.StringIndexOutOfBoundsException is thrown.

A sample execution is shown below:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20 at java.lang.String.substring(String.java:1950) at main.java.StringSubstringExample_v2.main(StringSubstringExample_v2.java:10)

String’s valueOf method

StringValueOfExample.java:

public class StringValueOfExample < public static void main(String[] args) < String str = "Java Code Geeks"; char[] charArray = str.toCharArray(); //The following statement throws an exception, because //the request index is invalid. String value = String.valueOf(charArray, 10, 10); >>

In this example we define a sample string and then, we retrieve its value as a char array. Then, we try to define a string, whose value will be initialized starting from the 10th index of the char array and will be 10 characters long. However, the requested index is much larger of the string’s length and thus, an java.lang.StringIndexOutOfBoundsException is thrown. A sample execution is shown below:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20 at java.lang.String.(String.java:199) at java.lang.String.valueOf(String.java:3019) at main.java.StringValueOfExample.main(StringValueOfExample.java:10)

How to deal with the StringIndexOutOfBoundsException

This exception can be easily solved once you make use of the stack trace provided by the Java Virtual Machine (JVM). Once you detect the method that threw the java.lang.StringIndexOutOfBoundsException , then you must verify that the provided arguments are valid. Check that the provided offset points to a valid index and that the count argument does not point to indices greater than the size of the string itself.

Читайте также:  What is java remote method invocation

Download the Eclipse Project

Download
You can download the full source code of this example here: StringIndexOutOfBoundsExceptionExamples.zip.

Источник

Exception thrown java lang stringindexoutofboundsexception

Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

Constructor Summary

Constructs a new StringIndexOutOfBoundsException class with an argument indicating the illegal index.

Method Summary

Methods declared in class java.lang.Throwable

Methods declared in class java.lang.Object

Constructor Detail

StringIndexOutOfBoundsException

public StringIndexOutOfBoundsException()

StringIndexOutOfBoundsException

StringIndexOutOfBoundsException

public StringIndexOutOfBoundsException​(int index)

Constructs a new StringIndexOutOfBoundsException class with an argument indicating the illegal index. The index is included in this exception’s detail message. The exact presentation format of the detail message is unspecified.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

How to Handle String Index Out Of Bounds Exception in Java

How to Handle String Index Out Of Bounds Exception in Java

The StringIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access the character of a string at an index which is either negative or greater than the length of the string.

For some methods of the String class, such as the charAt method, this exception is also thrown when the index is equal to the size of the string.

Since the StringIndexOutOfBoundsException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. It can be handled in code using a try-catch block.

What Causes StringIndexOutOfBoundsException

A Java string is a collection of characters which has a range of [0, length of string]. When an attempt is made to access the characters with limits that fall outside the range of the string, the StringIndexOutOfBoundsException is thrown. Therefore, this exception occurs when the index of a character does not exist in the string.

Some methods that throw a StringIndexOutOfBoundsException with invalid specified arguments are:

  • String.charAt(int index) — Returns the character at the specified index. The index can have a range of [0, length — 1]. If the specified index does not belong to this range, a StringIndexOutOfBoundsException occurs.
  • CharSequence.subSequence(int beginIndex, int endIndex) — Returns a new character sequence based on specified arguments. The StringIndexOutOfBoundsException is thrown if any index is negative, the endIndex is greater than the length of the string or the beginIndex is greater than the endIndex .
  • String.substring(int beginIndex) — Returns a substring beginning with the character at the specified index. If the beginIndex is negative or greater than the length of the string, a StringIndexOutOfBoundsException is thrown.
  • String.substring(int beginIndex, int endIndex) — Returns a substring beginning with the character at the specified index, extending until the character at (endIndex — 1) . The StringIndexOutOfBoundsException is thrown if any index is negative, the endIndex is greater than the length of the string or the beginIndex is greater than the endIndex .
  • String.valueOf(char[] data, int offset, int count) — Returns the string representation of the specified character array argument. If any index is negative or if (offset + count) is greater than the size of the specified array, a StringIndexOutOfBoundsException is thrown.
Читайте также:  Input integer value in java

Also, all constructors of the String class that contain an array in their argument list throw a StringIndexOutOfBoundsException when the specified offset and count arguments are invalid.

StringIndexOutOfBoundsException Example

Here is an example of a StringIndexOutOfBoundsException thrown when an attempt is made to retrieve the character at a specified index that falls outside the range of the string:

public class StringIndexOutOfBoundsExceptionExample < public static void main(String args[]) < String str = "My String"; System.out.println(str.charAt(9)); > >

In this example, the String.charAt() method is used to access the character at index 9. Since this method only allows a range of [0, length — 1] for the string, using index 9 throws the StringIndexOutOfBoundsException as it falls outside the range:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:711) at StringIndexOutOfBoundsExceptionExample.main(StringIndexOutOfBoundsExceptionExample.java:4)

How to Handle StringIndexOutOfBoundsException

The StringIndexOutOfBoundsException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps:

  • Surround the statements that can throw an StringIndexOutOfBoundsException in try-catch blocks
  • Catch the StringIndexOutOfBoundsException
  • Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.
  • Check the length of the string using String.length() and access its characters that fall within the range.

The code in the earlier example can be updated with the above steps:

public class StringIndexOutOfBoundsExceptionExample < public static void main(String args[]) < String str = "My String"; try < System.out.println(str.charAt(9)); > catch(StringIndexOutOfBoundsException e) < System.out.println("String index out of bounds. String length: " + str.length()); > > >

Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

String index out of bounds. String length: 9

Track, Analyze and Manage Errors with Rollbar

Rollbar in action

Finding exceptions in your Java code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring, tracking and triaging, making fixing Java errors and exceptions easier than ever. Sign Up Today!

Источник

Оцените статью