devxlogo

How to Check if Index Is in Range [0, n)

How to Check if Index Is in Range [0, n)

In order to check whether or not an index is in range [0, n) we can rely on a “if” statement, as below:

if (index = n) { ... }

But, Java 9 comes with the method bjects.checkIndex() that checks if the given index is in range [0, n).

This method returns the given index or throws an IndexOutOfBoundsException:

import java.util.Objects;...int indexChecked = Objects.checkIndex(index, n);
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist