DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java BasicsTopic 37 of 59
←PreviousPrevNextNext→

Looping Through Java Arrays - Complete Guide

Introduction to Array Looping

Looping through arrays is a core operation in Java. It allows you to read, update, and process each element in an array systematically.

Java provides multiple looping constructs—traditional for loops, enhanced for loops, while loops, and do-while loops—each suited for different scenarios.

For Loop with Index

The traditional for loop gives full control over the index, making it useful when you need both the element and its position, or when you want to iterate in a custom order.

Example
public class ForLoopWithIndex {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Basic for loop
        System.out.println("Basic for loop:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Index " + i + ": " + numbers[i]);
        }
        
        // Skipping elements
        System.out.println("\nEvery second element:");
        for (int i = 0; i < numbers.length; i += 2) {
            System.out.println("Index " + i + ": " + numbers[i]);
        }
        
        // Reverse order
        System.out.println("\nReverse order:");
        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.println("Index " + i + ": " + numbers[i]);
        }
        
        // Partial iteration
        System.out.println("\nFirst 3 elements:");
        for (int i = 0; i < 3 && i < numbers.length; i++) {
            System.out.println("Index " + i + ": " + numbers[i]);
        }
        
        // Modifying elements
        System.out.println("\nDoubling values:");
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = numbers[i] * 2;
            System.out.println("Index " + i + ": " + numbers[i]);
        }
        
        // Nested for loop for 2D array
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        
        System.out.println("\n2D array iteration:");
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output
Basic for loop:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50

Every second element:
Index 0: 10
Index 2: 30
Index 4: 50

Reverse order:
Index 4: 50
Index 3: 40
Index 2: 30
Index 1: 20
Index 0: 10

First 3 elements:
Index 0: 10
Index 1: 20
Index 2: 30

Doubling values:
Index 0: 20
Index 1: 40
Index 2: 60
Index 3: 80
Index 4: 100

2D array iteration:
1 2 3 
4 5 6 
7 8 9 

Enhanced For Loop (For-Each)

The enhanced for loop simplifies iteration when only element values are needed. It improves readability but does not give direct access to indices or allow modification of array elements in place.

Example
public class EnhancedForLoop {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
        
        // Simple for-each loop
        System.out.println("Numbers:");
        for (int number : numbers) {
            System.out.println(number);
        }
        
        System.out.println("\nFruits:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        
        // Modification attempt (does not change array)
        System.out.println("\nTrying to modify elements (affects local variable only):");
        for (int number : numbers) {
            number = number * 2;
            System.out.println(number);
        }
        
        System.out.println("Original array unchanged: " + java.util.Arrays.toString(numbers));
        
        // Aggregation
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        System.out.println("Sum: " + sum);
        
        // Finding maximum
        int max = numbers[0];
        for (int number : numbers) {
            if (number > max) max = number;
        }
        System.out.println("Max: " + max);
        
        // Condition counting
        int count = 0;
        for (int number : numbers) {
            if (number > 25) count++;
        }
        System.out.println("Numbers greater than 25: " + count);
        
        // With object arrays
        Person[] people = {
            new Person("Alice", 25),
            new Person("Bob", 30),
            new Person("Charlie", 35)
        };
        
        System.out.println("\nPeople:");
        for (Person person : people) {
            System.out.println(person.getName() + " - " + person.getAge());
        }
    }
}

class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() { return name; }
    public int getAge() { return age; }
}
Output
Numbers:
10
20
30
40
50

Fruits:
Apple
Banana
Orange
Mango

Trying to modify elements (affects local variable only):
20
40
60
80
100
Original array unchanged: [10, 20, 30, 40, 50]
Sum: 150
Max: 50
Numbers greater than 25: 3

People:
Alice - 25
Bob - 30
Charlie - 35

While and Do-While Loops with Arrays

While and do-while loops provide more control over iteration, useful for conditional traversal, searches, or processing until a specific condition is met.

Example
public class WhileDoWhileWithArrays {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        
        // While loop
        System.out.println("While loop:");
        int i = 0;
        while (i < numbers.length) {
            System.out.println("Index " + i + ": " + numbers[i]);
            i++;
        }
        
        // Do-while loop
        System.out.println("\nDo-while loop:");
        int j = 0;
        do {
            System.out.println("Index " + j + ": " + numbers[j]);
            j++;
        } while (j < numbers.length);
        
        // Condition-based termination
        int[] data = {5, 15, 25, 35, 45, 55, 65};
        System.out.println("\nWhile loop until value > 50:");
        int index = 0;
        while (index < data.length && data[index] <= 50) {
            System.out.println("Value: " + data[index]);
            index++;
        }
        
        // Searching for an element
        int[] values = {10, 20, 30, 40, 50, 60};
        int searchValue = 40;
        int pos = 0;
        boolean found = false;
        System.out.println("\nSearching for " + searchValue + ":");
        while (pos < values.length && !found) {
            if (values[pos] == searchValue) {
                found = true;
                System.out.println("Found at index " + pos);
            }
            pos++;
        }
        if (!found) System.out.println("Value not found");
        
        // Filtering values
        int[] mixedNumbers = {15, 7, 22, 9, 31, 12, 45};
        System.out.println("\nFiltering even numbers:");
        int k = 0;
        int count = 0;
        while (k < mixedNumbers.length) {
            if (mixedNumbers[k] % 2 == 0) {
                System.out.println("Even number: " + mixedNumbers[k]);
                count++;
            }
            k++;
        }
        System.out.println("Found " + count + " even numbers");
    }
}
Output
While loop:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50

Do-while loop:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50

While loop until value > 50:
Value: 5
Value: 15
Value: 25
Value: 35
Value: 45

Searching for 40:
Found at index 3

Filtering even numbers:
Even number: 22
Even number: 12
Found 2 even numbers

Best Practices for Array Looping

  • ✅ Use enhanced for loops when only values are needed
  • ✅ Use traditional for loops for index-based operations or modifications
  • ✅ Always check array bounds to avoid ArrayIndexOutOfBoundsException
  • ✅ Use while/do-while when iteration depends on conditions, not fixed indices
  • ✅ Apply break and continue carefully to control loop flow
  • ✅ Prefer enhanced for loops for readability when appropriate
  • ✅ Use System.arraycopy() or utility methods for copying instead of manual loops
  • ✅ Consider Java 8+ Stream API for more complex operations like filtering and mapping
Test your knowledge: Looping Through Java Arrays - Complete Guide
Quiz Configuration
4 of 10 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java BasicsTopic 37 of 59
←PreviousPrevNextNext→