ArrayIndexOutOfBoundsException

T

tiewknvc9

Hi.

Im getting an ArrayIndexOutOfBoundsException when using an array, and
while I know I can use a try catch statement to get around this
problem, I was wondering if there was a way to test to see if the
element exists instead.

for instance.

if (myArray[67].exists){
//then do something with myArray[67]
}

thanks.
 
A

Alan Krueger

tiewknvc9 said:
I got it

if (67 > myArray.length){
//not exception!
}

Actually, I think you mean "index < myArray.length". If the index is
greater than the length (or even equal to it), you will get an exception.
 
F

Finomosec

Alan said:
Actually, I think you mean "index < myArray.length". If the index is
greater than the length (or even equal to it), you will get an exception.

Be aware, that arrays in Java are zero-based.

A typical loop over an array looks like this:

String[] strings = new String[]{"string0", "string1", "string2"};

// zero-based:
// strings[0] ==> "string0"
// strings[1] ==> "string1"
// strings[2] ==> "string2"
// strings.length == 3

for (int i = 0; i < strings.length; i++) {
String current = strings;
// do something with it ...
System.out.println(i + ": " + current);
}

This way you will never get any ArrayIndexOutOfBoundsExceptions ...

Greetings Finomosec;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top