Why is this an issue?

Java 21 adds new String.indexOf methods that accept ranges (beginIndex, to endIndex) rather than just a start index. A StringIndexOutOfBounds can be thrown when indicating an invalid range, namely when:

How to fix it

Code examples

Noncompliant code example

String hello = "Hello, world!";
int index = hello.indexOf('o', 11, 7); // Noncompliant, 11..7 is not a valid range

Compliant solution

String hello = "Hello, world!";
int index = hello.indexOf('o', 7, 11); // Compliant

Noncompliant code example

String hello = "Hello, world!";
int index = hello.indexOf('o', -1, 11); // Noncompliant, because beginIndex is negative

Compliant solution

String hello = "Hello, world!";
int index = hello.indexOf('o', 0, 11); // Compliant

Resources