What is Objects.checkFromIndexSize in Java?
What is checkFromIndexSize?
The checkFromIndexSize method is a Objects class.
This method is used to check whether the fromIndex input to the sum of the fromIndex inputsize input of fromIndex is within bounds of zero and the input length.
The fromIndex, size, 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.
-
The
fromIndexis less than zero. -
The
sizeis less than zero. -
The
lengthis less than zero. -
The sum of
sizeandfromIndexis greater than thelength.
This method was introduced in Java 9. To use the checkFromIndexSize method, import the following module:
java.util.Objects
Syntax
public static int checkFromIndexSize(int fromIndex, int size, int length)
Parameters
-
int fromIndex- the lower bound of the sub-range. -
int size- the size of the sub-range. -
int length- the upper bound of the range.
Return type
This method returns fromIndex value if the sub-range is within bounds of the range.
Code
Example 1
The code below returns the fromIndex value, as the sub-range is within zero to length value.
import java.util.Objects;public class Main {public static void main(String[] args) {int fromIndex = 5;int size = 5;int length = 15;System.out.println(Objects.checkFromIndexSize(fromIndex, size, length));}}
Result
Explanation 1
We have imported the Objects class from java.util and used it to call the checkFromIndexSize() method.
The method takes the input of three parameters as declared from line 5 to line 7.
The program returns 5 as output and exits.
Example 2
In the code below, the fromIndex is passed as -1. When the program is run, it should throw IndexOutOfBoundsException.
import java.util.Objects;public class Main {public static void main(String[] args) {int fromIndex = -1;int size = 5;int length = 15;System.out.println(Objects.checkFromIndexSize(fromIndex, size, length));}}
Result
Explanation 2
As defined earlier in the shot, if we provide a negative number as input, the program throws an IndexOutOfBoundsException.