Start learning free

LESSON 60 OF 671 · STRINGS I

Exceeding String Bounds in Java

Lesson

When accessing string characters with indices, the most common problem we can run into is exceeding the string's bounds.

Remember, the characters of a string are normally indexed from 0 to length - 1.

Any index which is strictly greater than length - 1 is invalid.

When you try to access a character with an invalid index, Java throws a StringIndexOutOfBoundsException:

String car = "ford";

// Valid indices: 0, 1, 2, 3
System.out.println(car.charAt(0)); // Output: f
System.out.println(car.charAt(3)); // Output: d

// Invalid indices: 4, 30
System.out.println(car.charAt(4)); // StringIndexOutOfBoundsException
System.out.println(car.charAt(30)); // StringIndexOutOfBoundsException

This code would throw a StringIndexOutOfBoundsException: String index out of range: 4

In conclusion, we always want to double check our code to make sure that we don't exceed one string's bounds in our programs.


Assignment
Follow the Coding Tutorial and let's practice with string bounds!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check