What is Objects.checkFromToIndex in Java?

What is checkFromToIndex?

The checkFromToIndex method is a staticdeclared using the “static” keyword. These methods can be invoked without the need for creating an instance of a class. method of the Objects class.

This method is used to check whether the sub-range from the input fromIndex to the input toIndex is within bounds of zero and the input length.

The fromIndex, toIndex, and length are passed as arguments to the method.

Exceptions in checkFromToIndex

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

  1. The fromIndex is less than zero.

  2. The toIndex is less than zero.

  3. The length is less than zero.

  4. The fromIndex is greater than toIndex.

  5. The toIndex is greater than length.

This method was introduced in Java 9.

Required module

To use the checkFromToIndex method, import the following module:


java.util.Objects

Syntax


public static int checkFromToIndex(int fromIndex, int toIndex, int length)

Parameters

  • int fromIndex - the lower bound of the sub-range.

  • int toIndex - the upper bound of the sub-range.

  • int length - the upper bound of the range.

Return type

The method returns the fromIndex value if the sub-range is within bounds of zero to length.

Code

Example 1

The code below prints the fromIndex value because the sub-range is within the zero to length range.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
int fromIndex = 5;
int toIndex = 9;
int length = 15;
System.out.println(Objects.checkFromToIndex(fromIndex, toIndex, length));
}
}

Result

Explanation 1

We have imported class Objects from java.util and called the method checkFromToIndex() using the Objects class.

The method takes input from three parameters as declared from line 5 to line 7.

The program returns 5 as output and exits.

Example 2

The code below throws IndexOutOfBoundsException because the toIndex value is greater than the length value.

import java.util.Objects;
public class Main {
public static void main(String[] args) {
int fromIndex = 5;
int toIndex = 18;
int length = 15;
System.out.println(Objects.checkFromToIndex(fromIndex, toIndex, length));
}
}

Result

Explanation 2

As defined earlier in the shot, if toIndex is greater than length, the program will throw an IndexOutOfBoundsException.

Free Resources