Objects.checkFromIndexSize() validates an offset and range size against a sequence length, providing a convenient argument check when implementing APIs such as a three-argument InputStream.read(). section 5.2
Validate an InputStream range
class MyInputStream extends InputStream { @Override public int read(byte[] b, int off, int len) { Objects.checkFromIndexSize(off, len, b.length); … } } Use the method when an invalid offset or length should immediately cause an exception. section 5.2
class MyInputStream extends InputStream {
@Override
public int read(byte[] b, int off, int len) {
Objects.checkFromIndexSize(off, len, b.length);
…
}
}
Shows the focused pattern of checking a byte-array offset and length before processing the buffer. section 5.2
Avoid confusing this method with related checks or overlooking arithmetic overflow:
- Replacing offset + count with count <= length - offset avoids overflow after confirming all values are nonnegative. section 5.2
- Use checkIndex() for a single valid element and checkFromToIndex() for a from/to range; account for API-specific boundary contracts. section 5.2
