exceptions

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

    • 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)

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:

    • public char charAt(int index)

This methods returns the character of the specified index. The index ranges reside in [0, length()-1]. If the specified index does not belong in this interval, then an java.lang.StringIndexOutOfBoundsException is thrown.

    • public CharSequence subSequence(int beginIndex, int endIndex)

This method returns a new character sequence based on the specified arguments. It throws an java.lang.StringIndexOutOfBoundsException if any index is negative, or the endIndex is greater than the string’s length, or if the beginIndex is greater than <startIndex.

    • public String substring(int beginIndex)

This method returns a sub-string that begins with the character at the specified index. It throws an java.lang.StringIndexOutOfBoundsException if beginIndex is negative, or larger than the length of the string.

    • public String substring(int beginIndex, int endIndex)

This method returns a sub-string that begins with the character at the specified index and extends until the character at endIndex-1 index. It throws an java.lang.StringIndexOutOfBoundsException if any index is negative, or endIndex is larger than the string’s legnth, or the beginIndex is greater than <startIndex.

    • public static String valueOf(char[] data, int offset, int count)

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.

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.

Download the Eclipse Project

This was a tutorial about the java.lang.StringIndexOutOfBoundsException in Java.

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

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button