checkFromToIndex
?The checkFromToIndex
method is a 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.
checkFromToIndex
The method throws the IndexOutOfBoundsException
exception if any of the following conditions are true.
The fromIndex
is less than zero.
The toIndex
is less than zero.
The length
is less than zero.
The fromIndex
is greater than toIndex
.
The toIndex
is greater than length
.
This method was introduced in Java 9.
To use the checkFromToIndex
method, import the following module:
java.util.Objects
public static int checkFromToIndex(int fromIndex, int toIndex, int length)
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.
The method returns the fromIndex
value if the sub-range is within bounds of zero to length
.
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));}}
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.
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));}}
As defined earlier in the shot, if toIndex
is greater than length
, the program will throw an IndexOutOfBoundsException
.