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
Java Examples Java Videos Java ... ... You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ iterating-arrays-java
Java - Loop Through an Array - GeeksforGeeks
December 2, 2024 - In Java, looping through an array or Iterating over arrays means accessing the elements of the array one by one.
Discussions

For Loops and Arrays in Java - Stack Overflow
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 ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Coding with arrays and for loops
Implement a program like below. You should use an array to store the values and a for-loops to process. More on reddit.com
๐ŸŒ r/learnjava
8
5
March 4, 2025
performance - Fastest way to iterate an Array in Java: loop variable vs enhanced for statement - Stack Overflow
1 Does JVM create an iterator when it iterates over array with for-each loop? ... 497 What is the easiest/best/most correct way to iterate through the characters of a string in Java? More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How do you iterate through an array and delete an element? - Software Engineering Stack Exchange
I have an array and I can iterate through it. I know that it is impossible to change the size of an array; however, how do I take out a certain element that I not want in the array anymore? Exampl... More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
March 14, 2015
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);

๐ŸŒ
CodingBat
codingbat.com โ€บ doc โ€บ java-array-loops.html
CodingBat Java Arrays and Loops
Another common problem is searching through all the elements in an array to find a particular "target" value. The code is basically the standard for-all loop with an if-statement inside looking at each element. The example code below takes array and target arguments and searches through the ...
Find elsewhere
๐ŸŒ
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 - Itโ€™s not a new concept in computer science, but it was a big quality-of-life improvement for Java at the time it was introduced. You can read from the array in a way thatโ€™s easier to follow and harder to mess up by accident. This version of the loop is often called the โ€œfor-eachโ€ loop because thatโ€™s exactly what itโ€™s doing. It gives you one element at a time from the array, starting at the beginning and going through to the end.
๐ŸŒ
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]); } } }
๐ŸŒ
Reddit
reddit.com โ€บ r โ€บ learnjava โ€บ comments โ€บ 1j3asla โ€บ coding_with_arrays_and_for_loops
Coding with arrays and for loops : r/learnjava
March 4, 2025 - Scanner sc = new Scanner(in); out.print("Input 5 integers (space between, then enter) > "); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); int e = sc.nextInt(); int[] arrays = {a, b, c, d, e}; out.println("Array is: " + Arrays.toString(arrays)); out.print("Input a value to find > 1: "); int i = sc.nextInt(); I tried to do a for-loop but I genually have no idea how I'm supposed to do it...I sort of tried to attempt it for if the value is in range (just to make sure it works hence why I didn't add any if statements yet)
๐ŸŒ
Codecademy
codecademy.com โ€บ learn โ€บ apcs-arrays-and-loops โ€บ modules โ€บ apcs-two-dimensional-arrays โ€บ cheatsheet
Arrays and Loops: Two-Dimensional Arrays Cheatsheet | Codecademy
โ€œRow-major orderโ€ refers to ... the bottom right. In Java, row major ordering can be implemented by having nested loops where the outer loop variable iterates through the rows and the inner ......
๐ŸŒ
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
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 ...
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.

๐ŸŒ
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 - 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.
Top answer
1 of 3
6

The Java Collections framework is something that you should browse. There are also some types that aren't array-like (Set and Map) but you will find that you will use them often. There are many different types of collections, and some have advantages over others for certain types of operations.

Classic arrays

First, the thing that isn't in the collections framework. The Array. Not ArrayList, but rather the classic int[]. The advantage of the array is that it closely maps to what memory is. foo[42] is to lookup. Many system level calls that give you a fixed number of items are arrays and they are good to know. "1,2,3".split(",") returns back an array for example.

The problem with arrays is that they aren't that flexible. Adding an element to the end of an array that already is at is maximum capacity means allocating a new, larger array and then doing an System.arraycopy() (javadoc) to copy all the elements from one array to another array in a timely manner.

To remove an element from the list you need to remove it and then walk the remainder of the list to have everything be contagious again. If you want to remove foo[4] from the list, you then assign foo[4] = foo[5] and foo[5] = foo[6] and so on down to the end of the list. Thats if you have to do it by hand. You can also use that System.arraycopy mentioned to do it for you given the right set of arguments. Something like:

System.arraycopy(foo,5,foo,4,foo.length - 4);

I might have that wrong, but thats the general idea. Copying the array back on itself. It should work.

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

Lists

As you see, arrays are a bit awkward to work with. You've got do it all by hand. Its good to know, but a pain to practice. There are two lists that are in common use that make this easier for you. For the most part, Lists look like arrays.

List<Integer> foo = ...;
foo.get(4);
foo.remove(5);

You call methods on them, but you are fetching the 4th element via method call instead of via direct access through the array. See that foo.remove(5). Thats it. You're done. You have removed an element from the list and deleted it. Much easier to remember.

ArrayList

The ArrayList is backed by an Array. This means that doing foo.get(4) runs fast, but foo.add(42, foo.size()+1) is likely to be slow because it has to do all of that moving of things around to allocate a new list (yes, I know that the list can be longer than the size, but lets assume that its the same size as its actual list).

Instead of having to remember how to do all the shuffling, you've got nice methods to do your work for you. It doesn't mean that its not done (the work is still done behind the scenes of the interface), but its something that you don't have to worry about.

So, the ArrayList is for:

  • fast get (O(1))
  • slow remove and insert (O(length))
  • slow append when full (O(length))

LinkedList

For some reason, everyone's goto list implementation is the ArrayList. I don't know why. Many times when I'm working with Lists, the LinkedList is the one that is more applicable. You keep adding things to the end. Rarely do you want the nth element. You just want to iterate over them.

This is what the LinkedList is good for. It does fast remove and append and its iterator is just as fast as the ArrayList. Its just if you want foo.get(400) its going to be a bit slower than the ArrayList implement.

The LinkedList is also a Deque too, but people forget about that. That lets you access the LinkedList as a double ended queue (nice for implementing a Stack or Queue).

So, if you are just appending and iterating, the LinkedList is for you.

  • Get is slowish (O(index))
  • Fast append (O(1))
  • Remove and insert is slowish (O(index))

Note that the O(index) there is a bit of an award bit. It will index depending on which way is faster to get there (from the end or start). So if the LinkedList is 100 long, and you get(10), it starts from the start. If you ask for get(90), it starts from the end. So get(index) is never more than get(length/2), but thats all just factors that don't matter when looking at Big O.

2 of 3
1

If you must really do this using an array, then you will need to:

  • copy all elements of the array after the element being deleted down by one position to cover the removed element.

  • resize your array to be smaller by one element.

Copying elements down by one position can be done either by writing a loop yourself, or by invoking System.arraycopy( src, srcPos, dest, destPos, length).

Resizing the array can be done like this: myArray = Arrays.copyOf( myArray, newCapacity ).

That having been said, if you have any need to manipulate the length of the array, then definitely go with ArrayList instead of using arrays. This wheel has already been invented.

๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ how to loop through an array recursively w/out arrays class
r/javahelp on Reddit: How to Loop Through an Array Recursively W/out Arrays Class
December 3, 2021 -

Let's say I have some void method called recursivePrintArray that takes in an array of ints like this...

public static void recursivePrintArray(int[] array) {	
	
    System.out.println("...");
		
}
    public static void main(String[] args) {

	int[] nums = {1, 2, 3, 4};
		
	recursivePrintArray(nums);

}

How would I recursively go through and print the elements of nums without using the Arrays class or an iterator?

๐ŸŒ
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
๐ŸŒ
Zero To Mastery
zerotomastery.io โ€บ blog โ€บ enhanced-for-loop-java
How To Use Enhanced For Loops In Java (aka 'foreach') | Zero To Mastery
January 26, 2024 - Always improving, Java 5 introduced the enhanced for loop as a part of its syntax enrichment. The enhanced for loop, otherwise known as a foreach loop, offers a simplified way to iterate over collections and arrays.
๐ŸŒ
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 by starting at the back of the array and move toward the front during each time through the loop. In the example below, the method getIndexOfLastElementSmallerThanTarget returns the index of the last element in the array that is smaller than the given argument.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
3 weeks ago - The for-each loop in Java (introduced in Java 5) provides a simple, readable way to iterate over arrays and collections without using indexes.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 381420 โ€บ java โ€บ loop-arraylist-arrays
loop through arraylist of arrays (Java in General forum at Coderanch)
November 13, 2006 - We also know that each detail contains a List of its own, so in order to iterate through that list we set up another loop: You didn't say what type of object was in the data List, so I used "Whatever". That help? The upshot is, when you have nested lists/arrays, you need nested loops to iterate through them.