Wednesday, June 29, 2022

How to loop through an Array in Java? Example Tutorial

Hello there, If you want to loop over an array in Java but not sure how to do that then you have come to the right place. Earlier, I have shared many Java array tutorials and the best Java courses for beginners, and today, I am going to teach you how to iterate over an array in Java. There are multiple ways to loop over an array in Java, like you can use a for loop, an enhanced for loop, a while loop, or a do-while loop. Since while and do-while needs a condition to terminate they often depend upon the content of the array like stop when the current element is null or even or odd etc. If you just want to iterate over an array to access each element like loop over an array and print each entry then you should use either for loop or the enhanced for loop.

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 about counts.

This results in clean code and also eliminates the possibility of one-off errors. In this article, I'll show you 2 ways to iterate over an array, first by using traditional for loop and second by using enhanced for loop of Java 1.5.

An array is a special data structure that you will find in every possible programming language including on scripting language like bash. Array stores elements into the contiguous memory location which means if you know the memory location of one element you can access others, but since Java doesn't allow you to access an array element using memory address, you need to use the index. 

If you want to learn more about not just the array but other fundamental data structures like the linked list and the binary tree then I highly recommend you to join a comprehensive data structure and algorithm course in Java. If you need a recommendation, I suggest you join Data Structures and Algorithms: Deep Dive Using Java course by Tim Buchalaka and his team on Udemy. 





How to loop Over an Array in Java [Examples]

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.

There are several differences between looping through an array using for loop and enhanced for loop like first is more flexible, gives more power but also error-prone. It gives you an index to track the current element, you can go forward and backward by incrementing or decrementing counter but it also susceptible to one-off error where programmer misses either first or last element of an array.


On the other hand, enhanced for loop provides the simplest way to loop through an array. It was originally intended to loop over collections like List, Set or Queue, but you can also use an array with enhanced for loop. It doesn't require the programmer to maintain the counter, instead, it automatically moves from one element to another.

It's best suited for iteration where you want to access each element of array one by one, but it's not as powerful as looping over traditional for loop because you can not jump elements, you cannot traverse backward etc.

By the way, if you are new to Java and want to learn Java in a more structured way then I also recommend you to check out The Complete Java Masterclass course on Udemy. It's a great course to learn Java, it's also the most comprehensive and up-to-date with 80+ hours of content. 

How to loop through an array in Java




Java Program to loop over an Array in Java

Here is our Java program which will teach you how to use both simple for loop and enhanced for loop of Java 1.5 to traverse over an array in Java.

package hello;

public class ArrayTester{

public static void main(String[] args) {

// how to loop over an integer array
int[] primes = {2, 3, 5, 7, 11, 13, 17};

// looping using for loop
System.out.println("looping over an array using for loop");
for(int i=0; i< primes.length; i++){
System.out.println("current element is: " + primes[i]);
}

// looping using enhanced for loop of Java 5
System.out.println("looping over an array using enhanced for loop");
for(int number: primes){
System.out.println(number);
}

}
}

Output
looping over an array using for loop
current element is: 2
current element is: 3
current element is: 5
current element is: 7
current element is: 11
current element is: 13
current element is: 17
looping over an array using enhanced for loop
2
3
5
7
11
13
17

You can see both methods work in the same way for simple iteration. Depending upon your situation and algorithm you may need to traverse array from the last element to backward,  you may need to jump over element like printing every second elements etc. For such cases, prefer the traditional for loop. It gives you full control of the iteration process to the programmer.


Important points about Array and Loop in Java

1) You can use any loop like for, while, and do-while or enhanced for loop to loop over an array.

2) If you need a counter to hold the current index of the array to implement your algorithm than use the for loop.

3) If your looping depends upon the current element then use a while and do-while loop.

4) If you just want to iterate or traverse over all elements of an array then use enhanced for loop. It doesn't need any counter and much more readable than traditional loops.

5) Use the common or simple for loop if you want full control of looping over an array. It allows both forward and backward traversal and jumping over elements by incrementing the counter.

6) You need to use the nested loops like a loop inside another loop to iterate over a multi-dimensional array in Java.


That's all about how to loop through an array in Java an array in Java. As I said, you have multiple ways to loop over an array, depending upon your requirement and situation you can use any of the mentioned approaches.

In short, use for loop if you need to hold the counter which points to current index and uses enhanced for loop if you just want to iterate over all elements of an array. Use while and do-while if your looping depends upon the element of an array, like stop looping when the current element is null etc.



Other Java Array tutorials You may like
  • How to remove duplicate elements from ArrayList in Java? (tutorial)
  • Top 5 courses to learn Java Collections and Streams (best courses)
  • When to use ArrayList over LinkedList in Java? (answer)
  • Top 5 Courses to learn Spring MVC for beginners (spring courses)
  • How to loop through an ArrayList in Java? (tutorial)
  • 10 Advanced Core Java Courses for Programmers (advanced courses)
  • How to synchronize an ArrayList in Java? (read)
  • Top 5 Courses to become full-stack Java developers (online courses)
  • How to create and initialize ArrayList in the same line? (example)
  • Top 5 Java Concurrency and thread courses (best courses)
  • Difference between ArrayList and HashMap in Java? (answer)
  • Difference between an Array and ArrayList in Java? (answer)
  • How to reverse an ArrayList in Java? (example)
  • How to get a sublist from ArrayList in Java? (example)
  • 10 Best Spring Boot Courses for Java developers (boot courses)
  • Difference between ArrayList and Vector in Java? (answer)
  • 10 Free Spring Courses for Java programmers (Free courses)
  • How to sort an ArrayList in descending order in Java? (read)
  • Difference between ArrayList and HashSet in Java? (answer)
  • How to convert CSV String to ArrayList in Java? (tutorial)

Thanks for reading this article so far. If you like this Java Array loop-over tutorial then, please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S. - If you are new to the Java world and looking to self-teach Java to yourself, I suggest you checkout Java Tutorial for Complete Beginners (FREE) course from Udemy. More than 1 million Java programmers have joined this course to learn Java online, and it's completely free. 

4 comments :

erhun said...

I want to ask that is there any explanation about how Array are supported enhanced for loop. As i know which is describe below too enhanced for loop can be used with Collections which implements Iterable interface. So how java array can also support it although it is not implement the Iterable interface? Do you and resource or link to answer this question?

"On the other hand enhanced for loop provides the simplest way to loop through an array. It was originally intended to loop over collection e.g. List, Set or Queue, but you can also use an array with enhanced for loop. It doesn't require the programmer to maintain the counter, instead, it automatically moves from one element to another."

javin paul said...

@erhun, you should check out Java Specification it clearly says that array supports iteration via enhanced for loop. Since array is native construct and implemented inside JVM, you cannot see it, but Java specification should give you enough detail.

P N BABU said...

how to find duplicate numbers from integer Array using HashMap

javin paul said...

you can use the same method, go through integer array, store them as key in HashMap and when put return false, its a duplicate because HashMap doesn't allow duplicate keys. Are you getting any error doing this?

Post a Comment