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