Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

objects
java
checkindex

What is Objects.checkIndex in java?

Abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

objects
java
checkindex

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring