What is Objects.checkIndex in java?

What is 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.

Exceptions in checkIndex

The method throws IndexOutOfBoundsException if any of the following conditions are true:

  1. The index is less than zero.

  2. The length is less than zero.

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

Syntax


public static int checkIndex(int index, int length)

Parameters

  • int index - index value

  • int length - length value, i.e., the upper bound

Code

Example 1

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));
}
}

Result 1

Example 2

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));
}
}

Result 2

Example 3

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));
}
}

Result 3

Free Resources