55 lines
1.7 KiB
Plaintext
55 lines
1.7 KiB
Plaintext
== 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:
|
|
|
|
* `beginIndex > endIndex` (eg: `beginIndex` and `endIndex` arguments are mistakenly reversed)
|
|
* `beginIndex < 0` (eg: because the older `String.indexOf(what, fromIndex)` accepts negative values)
|
|
|
|
|
|
== How to fix it
|
|
|
|
- Use `String.indexOf(what, beginIndex, endIndex)` instead of `String.indexOf(what, endIndex, beginIndex)`.
|
|
- Use `String.indexOf(what, 0, endIndex)` instead of `String.indexOf(what, -1, endIndex)`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
String hello = "Hello, world!";
|
|
int index = hello.indexOf('o', 11, 7); // Noncompliant, 11..7 is not a valid range
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
String hello = "Hello, world!";
|
|
int index = hello.indexOf('o', 7, 11); // Compliant
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
String hello = "Hello, world!";
|
|
int index = hello.indexOf('o', -1, 11); // Noncompliant, because beginIndex is negative
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=2,diff-type=compliant]
|
|
----
|
|
String hello = "Hello, world!";
|
|
int index = hello.indexOf('o', 0, 11); // Compliant
|
|
----
|
|
|
|
== Resources
|
|
|
|
* Java Documentation - https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html#indexOf(int,int,int)[String.indexOf(int, int, int)]
|
|
* Java Documentation - https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html#indexOf(java.lang.String,int,int)[String.indexOf(java.lang.String,int,int)]
|
|
|
|
|