checkIndex?The method checkIndex is a static method of the Objects class.
This method checks whether the input index is within bounds of the input length:
0 <= index < length
The index and length are passed as arguments to the method.
checkIndexThe method throws IndexOutOfBoundsException if any of the following conditions are true:
The index is less than zero.
The length is less than zero.
The index is greater than length.
This method was introduced in Java 9.
To use the checkIndex method, import the following module:
java.util.Objects
public static int checkIndex(int index, int length)
int index - index value
int length - length value, i.e., the upper bound
In the code below, -1 is passed as an index value. So, executing the code should throw IndexOutOfBoundsException.
import java.util.Objects;public class Main {public static void main(String[] args) {int index = -1;int length = 10;System.out.println(Objects.checkIndex(index, length));}}
In the code below, -1 is passed as the length value. So, executing the code should throw IndexOutOfBoundsException.
import java.util.Objects;public class Main {public static void main(String[] args) {int index = 4;int length = -1;System.out.println(Objects.checkIndex(index, length));}}
In the code below, 4 is passed as index value and 10 as the length value.
Executing the code should return the index value, as the index is within bounds of the length.
import java.util.Objects;public class Main {public static void main(String[] args) {int index = 4;int length = 10;System.out.println(Objects.checkIndex(index, length));}}