Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2006

Tip: Looking for answers? Try searching our database.

ArrayIndexOutOfBoundsException

Thread view: 
tiewknvc9 - 15 Feb 2006 19:20 GMT
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.
tiewknvc9 - 15 Feb 2006 19:38 GMT
I got it

if (67 > myArray.length){
 //not exception!
}
Alan Krueger - 16 Feb 2006 00:07 GMT
> 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.
Finomosec - 16 Feb 2006 20:53 GMT
Alan Krueger schrieb:
>> I got it
>>
[quoted text clipped - 4 lines]
> 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[i];
    // do something with it ...
    System.out.println(i + ": " + current);
}

This way you will never get any ArrayIndexOutOfBoundsExceptions ...

Greetings Finomosec;
Roedy Green - 17 Feb 2006 05:12 GMT
>Be aware, that arrays in Java are zero-based.

in other words if you have an array of 10 elements ,they are numbered
0 to 9.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.