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
Arrays Loop Through an Array Real-Life Examples Multidimensional Arrays Code Challenge · Java Methods Java Method Challenge Java Method Parameters
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterating-arrays-java
Java - Loop Through an Array - GeeksforGeeks
December 2, 2024 - Example 3: We can also loop through an array using while loop. Although there is not much of a difference in for and while loop in this condition. While loop is considered effective when the increment of the value depends upon some of the condition. ... // 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++; } } }
🌐
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 ...
🌐
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]); } } }
🌐
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
First trace through it on paper keeping track of the array and the index variable. Then, run it to see if you were right. You can also follow it in the visualizer by clicking on the Show Code Lens button. We can use iteration with a for loop to visit each element of an array.
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.

🌐
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
The traditional loop uses a counter and allows you to iterate until the last element is reached i.e. counter is equal to the length of the array while enhanced for loop maintains that counter internally, allowing you to iterate without worrying ...
🌐
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.
Find elsewhere
🌐
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 - // Java program to iterate over ... n = {1, 2, 3, 4, 5}; // Using for loop System.out.println("Using for loop:"); for (int i = 0; i < n.length; i++) { System.out.println(n[i]); } // Using for-each loop System.out.println("Using ...
🌐
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
Java 1.5 foreach loop provides an elegant way to iterate over array in Java. In this programming tutorial, we will learn how to loop over String array in Java by using foreach loop.
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);

🌐
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.
🌐
Quora
quora.com › Can-you-iterate-through-an-array-in-Java-using-only-one-loop
Can you iterate through an array in Java using only one loop? - Quora
Answer (1 of 2): Yes, you can iterate through an array in Java using only one loop. You can use a [code ]for[/code] loop to achieve this. [code]int[] numbers = {1, 2, 3, 4, 5}; for (int i = 0; i
🌐
TutorialsPoint
tutorialspoint.com › what-are-the-different-ways-to-iterate-over-an-array-in-java
What are the different ways to iterate over an array in Java?
July 2, 2020 - import java.util.Arrays; public class IteratingArray { public static void main(String args[]) { //Creating an array int myArray[] = new int[7]; //Populating the array myArray[0] = 1254; myArray[1] = 1458; myArray[2] = 5687; myArray[3] = 1457; myArray[4] = 4554; myArray[5] = 5445; myArray[6] = 7524; //Printing Contents using for each loop System.out.println("Contents of the array: "); for (int element: myArray) { System.out.println(element); } } }
🌐
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 - 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 collections are designed.
🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
March 6, 2026 - The for-each loop in Java (introduced in Java 5) provides a simple, readable way to iterate over arrays and collections without using indexes.
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.