Java StringIndexOutOfBoundsException
StringIndexOutOfBoundsException is an index error for string operations. A scanner must have enough UTF-16 code units before it reads a fixed position.
A simple example
StringIndexOutOfBoundsException
- Start with Text "A"
- Do this Request a two-character prefix
- Result Too short
Syntax
code.substring(0, prefixLength)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead the depot prefix on a damaged label
A parcel scanner expects a three-character depot prefix. A torn label supplies only two characters, so the parcel should go to manual sorting before the software extracts the prefix.
class Main {
public static void main(String[] args) throws Exception {
String code = "NE";
int prefixLength = 3;
try {
System.out.println(code.substring(0, prefixLength));
} catch (StringIndexOutOfBoundsException shortLabel) {
System.out.println("Send to manual sorting");
}
}
}
Send to manual sorting
The prefix would end at index three, beyond this two-letter label. On JDK 21, String.substring reports that bounds failure with StringIndexOutOfBoundsException.
Route an intact warehouse label
A sorter sees a complete depot label on a replacement parcel. It checks the minimum length and extracts just the three letters used by the warehouse directory.
class Main {
public static void main(String[] args) throws Exception {
String label = "NTH-42";
System.out.println(label.length() >= 3 ? label.substring(0, 3) : "Rescan");
}
}
NTH
The end index is exclusive, so substring(0, 3) returns exactly three ASCII characters.
Read a complete lab identifier
A student scans a box showing the code BIO7. Extract the three-character prefix. A short scan must be repeated before the record is filed.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
"BIO7".substring(0,3);
System.out.println("Prefix available");
} catch (IndexOutOfBoundsException problem) {
System.out.println("Rescan");
}
}
}
Prefix available
What to watch for
IndexOutOfBoundsException is the documented general exception for substring. Use a length check when short input is expected.