Ankur Ankur - 1 year ago 76
Java Question

Iterating through a variable length Java array

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;

Answer Source
for(int i = 0; i < array.length; i++)


for(String value : array)

The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.

Just for completeness you can do the while loop this way:

int index = 0;

while(index < myArray.length)

But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download