Library contents

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

  1. Start with Text "A"
  2. Do this Request a two-character prefix
  3. Result Too short
Only one character is available. Check the length before extracting two.

Syntax

Java syntax
code.substring(0, prefixLength)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Read 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.

From the programString code = "NE"
ResultSend to manual sorting
Main.java
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");
        }
    }
}
Output
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.

Advertisements

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.

From the programString label = "NTH-42"
ResultNTH
Main.java
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");
    }
}
Output
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.

GivenBIO7 · take 3
Worked resultPrefix available
Code and output in Java
Java source
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");
        }
    }
}
Output
Prefix available

What to watch for

IndexOutOfBoundsException is the documented general exception for substring. Use a length check when short input is expected.

Documentation for StringIndexOutOfBoundsException