dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
May 31, 2019

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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);
Octavia Anghel
 
Thanks for your registration, follow us on our social networks to keep up-to-date