HOWTO · Java

How to Fix Java.Lang.StringIndexOutOfBoundsException: String Index Out of Range

Learn why charAt(0) fails on an empty Java string, how to check string index bounds, and when try-catch can help.

On this page

If charAt(0) is called on an empty string, Java throws StringIndexOutOfBoundsException because the string has no character at index 0. Check the string’s length before reading a character. For any nonempty string, valid character indices start at 0 and end at length() - 1.

Fix the java.lang.StringIndexOutOfBoundsException: String index out of range Error

Java string indices are zero-based. A string of length n has character indices from 0 through n - 1; an index equal to length() is already out of range. This is why charAt(0) fails when the string is empty. The smallest illustration is String value = ""; value.charAt(0);: it asks Java for a character that the string does not contain. This fragment is shown to explain the cause; no exception trace or run result is implied.

The next program uses a fixed string so you can see how a valid first-character lookup works. It keeps the input and access together, making the relationship between the string contents and the returned character clear. In a real method, the string may instead come from a form, file, network response, or another method. The same rule applies in each case: use an index only after establishing that the string contains a character there. Run this example:

class StringIndexExample {
    public static void main(String[] args) {
        String value = "DelftStack";
        System.out.println(value.charAt(0));
    }
}
D

For index 0, check that the string is nonempty before access. The guarded version below prints a fallback message when the value has no first character. It avoids calling charAt(0) in that branch, while the other branch reads the first character. The output shown is from the supplied run of this example.

class SafeStringIndexExample {
    public static void main(String[] args) {
        String value = "";
        if (!value.isEmpty()) {
            System.out.println(value.charAt(0));
        } else {
            System.out.println("No character at index 0");
        }
    }
}
No character at index 0

When the index comes from user input, validate the value before using it. For a string of length n, accept a character index only when 0 <= index && index < n. If the index is parsed from text, parse it first and decide how your application should respond when the text is not a number. Then apply the range check to the string you are about to read; checking one string and later reading a different or modified string can leave the check stale. If the caller needs a default character, choose one that has a defined meaning in your application, such as a documented placeholder. If no meaningful default exists, return a status, ask for corrected input, or skip the operation rather than silently substituting data.

Other string operations use related but distinct bounds. substring(beginIndex) accepts 0 <= beginIndex <= length(). For substring(beginIndex, endIndex) and subSequence(beginIndex, endIndex), require 0 <= beginIndex <= endIndex <= length(); the end index is exclusive, so it may equal the string length. String.valueOf(charArray, offset, count) requires nonnegative offset and count, and the requested range must fit within the array. These methods can throw StringIndexOutOfBoundsException when their bounds are not met. Check the arguments for the specific operation rather than assuming every string method uses the same pair of limits.

StringIndexOutOfBoundsException is unchecked, so a method does not have to declare it. A try-catch block can be appropriate when an unexpected bad index comes from a boundary you cannot validate earlier, or when you need to recover at that layer. It should not replace ordinary input and bounds checks: catching the failure after access does not make the requested character available. To debug a reported index-0 failure, inspect where the string is created, whether trimming or parsing changed it, and which branch reaches the access. The exception message and stack trace can vary across Java versions, so compare the actual index with the string’s current length() instead of relying on exact trace wording.