Found the answer

public class App {
    public static void main(String[] args) throws Exception {
        Car car = new Car();
        Bicycle bicycle = new Bicycle();
        Van van = new Van();

        Object[] racers = {car, bicycle, van};  

        for(Object x : racers) {
            System.out.println(x.getClass()); 

            ((Vehicle) x).go();  // this is the only change I made
        }
    }
}
Answer from Coder212_97 on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_arrays_loop.asp
Java Loop Through an Array
There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other data structures):
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ enhanced-for-loop
Java for-each Loop (With Examples)
class Main { public static void main(String[] args) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // iterating through an array using a for loop for (int i = 0; i < vowels.length; ++ i) { System.out.println(vowels[i]); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ iterating-arrays-java
Java - Loop Through an Array - GeeksforGeeks
December 2, 2024 - // Java program to iterate over an array // using while loop import java.io.*; class Main { public static void main(String args[]) { // taking an array int a[] = { 1, 2, 3, 4, 5 }; int i = 0; // Iterating over an array // using while loop while (i < a.length) { // accessing each element of array System.out.print(a[i] + " "); i++; } } } ... Example 4: We can also use the Arrays.stream() method. This Method is used to convert an Array into stream and then we can traverse stream using forEach() loop.
๐ŸŒ
Guru99
guru99.com โ€บ home โ€บ java tutorials โ€บ for-each loop in java
For-each loop in Java
November 8, 2024 - This is the conventional approach of the โ€œforโ€ loop: for(int i = 0; i< arrData.length; i++){ System.out.println(arrData[i]); } You can see the use of the counter and then use it as the index for the array. Java provides a way to use the โ€œforโ€ loop that will iterate through each element of the array...
๐ŸŒ
Java67
java67.com โ€บ 2013 โ€บ 08 โ€บ how-to-iterate-over-array-in-java-15.html
How to iterate over an Array in Java using foreach loop Example Tutorial | Java67
When we need to iterate through each element of an array and have to perform some operation on them e.g. filtering, transformation, or simply printing, the foreach loop comes to its full glory. There is not much difference between traditional for loop and Java 1.5 foreach loop, except that the former has counter and condition, which is checked after each iteration.
๐ŸŒ
CodingBat
codingbat.com โ€บ doc โ€บ java-array-loops.html
CodingBat Java Arrays and Loops
// (classic search-loop example) public int search(int[] nums, int target) { // Look at every element for (int i=0; i<nums.length; i++) { if (nums[i] == target) { return i; // return the index where the target is found } } // If we get here, the target was not in the array return -1; } For search problems, we generally write the loop in the standard way to go through all the elements, and then add if/break/return logic inside the loop to react to each element. As a matter of style, the search-loop solves two problems. It must iterate over all the elements, and it must figure out if the target is found or not.
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ csjava โ€บ Unit7-Arrays โ€บ topic-7-2-traversing-arrays.html
7.2. Traversing Arrays with For Loops โ€” CS Java
You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (&&) on line 14 to make sure that the loop doesnโ€™t go beyond the length of the array, because if you had an array that had less than 5 elements, you wouldnโ€™t want the code to try to double the 5th element which doesnโ€™t exist!
Find elsewhere
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ csjava โ€บ Unit7-Arrays โ€บ topic-7-3-arrays-with-foreach.html
7.3. Enhanced For-Loop (For-Each) for Arrays โ€” CS Java
To set up a for-each loop, use for (type variable : arrayname) where the type is the type for elements in the array, and read it as โ€œfor each variable value in arraynameโ€. for (type item: array) { //statements using item; } See the examples below in Java that loop through an int and a String ...
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ looping-through-an-array-in-java-with-the-for-each-loop-for-beginners-02f9020f90b8
Looping Through an Array in Java with the For Each Loop for Beginners
June 19, 2025 - Lists like ArrayList and sets like HashSet both qualify, as long as they can give back an iterator. ... But not every object works. Plain classes that donโ€™t implement Iterable arenโ€™t allowed here. You canโ€™t loop through a Map directly with this, either. You need to loop through its entry set, key set, or values collection, each of which is iterable. This keeps things consistent with how Java ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-iterate-over-arrays-using-for-and-foreach-loop
Java Program to Iterate Over Arrays Using for and for-each Loop - GeeksforGeeks
July 23, 2025 - Explanation: Here, both loops print the same array elements, but the for-each loop simplifies the iteration by eliminating the need for an index.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2016 โ€บ 02 โ€บ how-to-loop-through-array-in-java-with.html
How to loop through an Array in Java? Example Tutorial
Here is our sample Java program to demonstrate how to loop through an array in Java. For simplicity, we have chosen an int array but you can use any type of array, both primitive and reference types. This technique will work for all kind of array, except the multi-dimensional array. In order to loop through the two-dimensional array, you need to use nested loops as shown in the example given here. Though there are several ways to iterate over an array, in this article, I'll show you two of the most common ways, first by using traditional for loop which uses the array index to move forward or backward and the second one using enhanced for loop of Java 5.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
March 6, 2026 - Example 2: Iterating in a List using for-each loop ... import java.util.*; class Geeks { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(3); list.add(5); list.add(7); list.add(9); int max = Integer.MIN_VALUE; for (int num : list) { if (num > max) { max = num; } } System.out.println("List of Integers: " + list); System.out.println("Maximum element: " + max); } }
Top answer
1 of 5
3

The better question might be: Why wouldn't you want to use a FOR loop to iterate through an array? There are many ways to iterate through an Array or a collection and there is no law that states you have to use the FOR loop. In a lot of cases, it's simply the best to use for speed, ease of use, and readability. And yet, in other cases it is not:

The Array:

int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Display Array with the typical for loop:

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

Display Array with the enhanced for loop:

for(Integer num : array) {
    System.out.println(num);
}

Display Array with the do/while loop:

int i = 0;
do {
    System.out.println(array[i++]);
} while (i < array.length);

Display Array with the while loop:

int j = 0;
while (j < array.length) {
    System.out.println(array[j++]);
}

Display Array through Recursive Iteration:

iterateArray(array, 0);  // 0 is the start index.


// The 'iterateArray()' method:
private static int iterateArray(int[] array, int index) {
    System.out.println(array[index]);
    index++; 
    if (index == array.length) {
        return 0;
    }
    return iterateArray(array,index);
}

Display Array using Arrays.stream() (Java8+):

Arrays.stream(array).forEach(e->System.out.print(e + System.lineSeparator())); 

Display Array using IntStream (Java8+):

IntStream.range(0, array.length).mapToObj(index -> array[index]).forEach(System.out::println);

Choose your desired weapon....

2 of 5
1
Considering you have an array like : 
int[] array = {1,2,4,5,6};

You can use stream to iterate over it, apart from printing you can perform lot many thing over this array.

Arrays.stream(array).forEach(System.out::println);

Similarly you can do lot many action over collections as well:

List<String> myList = new ArrayList<>(); List
myList.add("A");
myList.add("B");
    

Stream.of(myList).forEach(System.out::println);

myList.forEach(System.out::println);

๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ enhanced-for-loops-in-java-how-to-use-foreach-loops-on-arrays
Enhanced For Loops in Java โ€“ How to Use ForEach Loops on Arrays
February 17, 2023 - The process here is the same with the last example. When number becomes an element in the array, it doubles the element's value and prints it to the console. You can use for-each loops in Java to iterate through elements of an array or collection.
๐ŸŒ
StudySmarter
studysmarter.co.uk โ€บ java for loop
Java For Loop: Syntax & Techniques | StudySmarter
An array in Java is a type of container that can store a fixed number of values of a single type. A For Loop can iterate through an array using the array's index, starting from the first element (index 0) and going up to the last element (array's length - 1).
Top answer
1 of 6
4

I am going to use a slightly different analogy, since a lot of answers are providing you with the correct information.

An array is just a list of sequential boxes containing values. Imagine it is a list of houses, each numbered from 0 (arrays in Java like many other programming languages start at 0 not 1) to n (in your case it is 2).

So if you were someone collecting donations from each house, you would start from the first house, 0, then proceed to the next house 1, then to the next house 2. You would keep track of which house you are visiting now, so that you also know which is the next one, and that is what the integer variable i is doing.

Printing numbers[i] does not make the loop cycle, in the same way that knocking on the first house does not mean you are going to knock at the second house.

The for loop is keeping track of which house numbers you need to visit next. It does it by the 3 statements it has in the same line:

for(int i = 0; i < number.length; i++)

The first statement is saying start from the first house (int i = 0). You could start wherever you like.

The second statement is saying, you want to go up to the last house, irrespective of how many houses there are. (i < number.length). This literally translates to keep looping as long as i is less than the size of the array. You might ask why isn't the condition <=. It is because we start from 0, so the length (size of the array) will be the number of the last house + 1. In your case, length = 2 + 1.

The third statement, is what is making you move to the next house. i++ is shorthand for saying i = i + 1. This statement takes place after every iteration of the loop.

So essentially your for loop first initialises i to 0, checks the condition (the second statement) and if the condition is satisfied does the first iteration, then it finally increments i, to start another iteration if the second condition is still satisfied. This loop is repeated until the second statement of your for expression is not true any more.

Finally all numbers[i] means is, since numbers is an array, the [ ] operator accesses the value at the specified index. So it is like knocking at the house with number i to see who lives there. Feeding the value to System.out.println() prints that value on screen.

2 of 6
2

Here's a breakdown of how the for-loop is executed (derived from this certification study guide)

Names as referred to below:

for(initialization code; 
    boolean expression; 
    update statements){
  body
}. 

The for-loop's parts are executed in this sequence:

  1. Initialization code
  2. If boolean expression is true, execute body, else exit the loop
  3. Body executes
  4. Execute update statements
  5. Return to Step 2

So when applied to your example, we can say:

Run initialization:

int i = 0

Iteration 1:

if(i < number.length) // -> if(0 < 3)
//run body
i++ //i becomes 1
//return to step 2 (new iteration)

Iteration 2:

if(i < number.length) // -> if(1 < 3) //i was incremented to 1
//run body
i++ //i becomes 2
//return to step 2 (new iteration)

Iteration 3:

if(i < number.length) // -> if(2 < 3) //i was incremented to 2
//run body
i++ //i becomes 3

Iteration 4 (not run):

//return to step 2 (new iteration)
if(i < number.length) // -> if(3 < 3)  -> condition not met
//condition not met, stop the loop

More specifically, I do not understand how i comes to represent the contents of the array

As you can see above, every time the loop body finishes executing, the update statements are executed, which makes the i variable increment, thus allowing to access a different index of the array.

This is done advisedly, if you change your update statements to i += 2, then some indexes of the array will be skipped.

๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ java-and-array-iteration-what-beginners-need-to-know-22a44dd32afb
Java and Array Iteration โ€” What Beginners Need to Know
June 17, 2024 - In this example, the loop starts with the index i initialized to 0. The condition i < numbers.length && numbers[i] != target makes sure that the loop continues as long as i is less than the length of the array and the current element is not equal to the target. The index i is incremented by 1 in each iteration until the target is found or the end of the array is reached. Beyond the basic iteration methods, Java offers more advanced techniques to iterate over arrays. These methods provide additional functionality and flexibility, making them suitable for more complex operations.
Top answer
1 of 6
69

If you're looping through an array, it shouldn't matter - the enhanced for loop uses array accesses anyway.

For example, consider this code:

public static void main(String[] args)
{
    for (String x : args)
    {
        System.out.println(x);
    }
}

When decompiled with javap -c Test we get (for the main method):

public static void main(java.lang.String[]);
  Code:
   0:   aload_0
   1:   astore_1
   2:   aload_1
   3:   arraylength
   4:   istore_2
   5:   iconst_0
   6:   istore_3
   7:   iload_3
   8:   iload_2
   9:   if_icmpge   31
   12:  aload_1
   13:  iload_3
   14:  aaload
   15:  astore  4
   17:  getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   20:  aload   4
   22:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   25:  iinc    3, 1
   28:  goto    7
   31:  return

Now change it to use an explicit array access:

public static void main(String[] args)
{
    for (int i = 0; i < args.length; i++)
    {
        System.out.println(args[i]);
    }
}

This decompiles to:

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   aload_0
   4:   arraylength
   5:   if_icmpge   23
   8:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_0
   12:  iload_1
   13:  aaload
   14:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   17:  iinc    1, 1
   20:  goto    2
   23:  return

There's a bit more setup code in the enhanced for loop, but they're basically doing the same thing. No iterators are involved. Furthermore, I'd expect them to get JITted to even more similar code.

Suggestion: if you really think it might make a significant difference (which it would only ever do if the body of the loop is absolutely miniscule) then you should benchmark it with your real application. That's the only situation which matters.

2 of 6
22

This falls squarely in the arena of micro-optimization. It really doesn't matter. Stylistically I always prefer the second because it's more concise, unless you need the loop counter for something else. And that's far more important than this kind of micro-optimization: readability.

That being said, For an ArrayList there won't be much difference but a LinkedList will be much more efficient with the second.