Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+14 votes

I am getting the correct output, but it comes along with an error message reading:

StringIndexOutOfBoundsException: String index out of range: 7

In the output it also states:

threw StringIndexOutOfBoundsException:
String index out of range: 7

What exactly does this mean and what can I do to fix this.

asked in CSC211_Winter2018 by (1 point)

2 Answers

+10 votes

When you use .length(), it will store the number more then the index number in the string. Because the string index always start with 0 base, but when you count the length of the string, it will start with number 1. So, it will give you this error: StringIndexOutOfBoundsException.

answered by (1 point)
+10 votes

Trang is exactly correct. I'll add some detail.

The indexing of the characters in a String begins at 0. So the String "dog" has character 'd' at index 0, character 'o' at index 1, and character 'g' at index 2.

The length method of the String class returns the number of characters in a string. For the string "dog" the length method returns 3, but notice that no character in "dog" is at index 3.

When you try to use charAt(3) with "dog", then the error would be String index out of range since for "dog" the range of indices is from 0 through 2.

In the Practice It problem, one of the test strings has 7 characters with valid indices 0-6, so 7 sould be an index out of range.

answered by (1 point)