Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking out of bounds in Java

I'm trying to check if an array location is out of bounds, what's the simplest way?

int[] arr;
populate(arr);
if(arr[-1] == null)
//out of bounds!

Would something like this work?

I'm pretty sure this can be done with a trycatch or a scanner but for just a simple small program, is there another way?

like image 412
dukevin Avatar asked Oct 30 '13 01:10

dukevin


People also ask

How do you check out of bound?

Simply use: boolean inBounds = (index >= 0) && (index < array. length); Implementing the approach with try-catch would entail catching an ArrayIndexOutOfBoundsException , which is an unchecked exception (i.e. a subclass of RuntimeException ).

What is out of bounds in Java?

The StringIndexOutOfBoundsException is an unchecked exception in Java that occurs when an attempt is made to access the character of a string at an index which is either negative or greater than the length of the string.

What is bounds checking in Java?

When your program is running and it tries to access an element of an array, the Java virtual machine checks that the array element actually exists. This is called bounds checking.

Does Java have bounds checking?

As a Java program is running, each time an array index is used it is checked to be sure that it is OK. This is called bounds checking, and is extremely important for catching errors.


1 Answers

Absolutely do not use try-catch for this. Simply use:

boolean inBounds = (index >= 0) && (index < array.length);

Implementing the approach with try-catch would entail catching an ArrayIndexOutOfBoundsException, which is an unchecked exception (i.e. a subclass of RuntimeException). Such exceptions should never (or, at least, very rarely) be caught and dealt with. Instead, they should be prevented in the first place.

In other words, unchecked exceptions are exceptions that your program is not expected to recover from. Now, there can be exceptions (no pun intended) to this here and there. For instance, it has become common practice to check if a string is parable as an integer by calling Integer.parseInt() on it and catching the potential NumberFormatException (which is unchecked). This is considered OK, but always think twice before doing something like that.

like image 185
arshajii Avatar answered Sep 29 '22 21:09

arshajii