liveBook · Manning

Objects.checkFromIndexSize

As explained in 100 Java Mistakes and How to Avoid Them

Objects.checkFromIndexSize is a Java utility method that validates an index and range size against a sequence length.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the API use, related checks, overflow risk, and boundary caveat without detailing implementation internals.
Examples
Uses a custom InputStream.read() implementation and large offset/count values that overflow addition.
What it assumes
Assumes familiarity with Java indexes, sequence lengths, exceptions, and implementing InputStream or collection methods.
What you can do after
Apply it via java.util.Objects when implementing methods that must reject invalid offset-and-size ranges.
How it connects
Connects range validation with InputStream, IndexOutOfBoundsException, checkIndex(), checkFromToIndex(), and List contracts.

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.