Alex Rivera | Logout

Iterating through a variable length array

Asked 2010-02-25T03:52:50.303
21

How do I iterate over a Java array of variable length.

I guess I would setup a while loop, but how would I detect that I have reached the end of the array.

I guess I want something like this [just need to figure out how to represent myArray.notEndofArray()]

index = 0;
while(myArray.notEndofArray()){
  system.out.println(myArray(index));
  index++;
}
Edit
Report

1 Answer

5

Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {
    System.out.println(o);
}
answered 2010-02-25T03:55:46.260

Your Answer