JAVA - Zero to Hero / Arrays and Strings

Array Traversal

πŸšΆβ€β™‚οΈ What is Array Traversal?

Array traversal means accessing each element of the array one by one, usually to:

  • Display elements

  • Perform calculations (sum, max, etc.)

  • Search for a specific value


πŸ” Using for Loop

int[] arr = {10, 20, 30, 40, 50};

for(int i = 0; i < arr.length; i++) {
    System.out.println("Element at index " + i + ": " + arr[i]);
}
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

πŸ”„ Using while Loop

int[] arr = {1, 2, 3, 4, 5};
int i = 0;

while(i < arr.length) {
    System.out.println(arr[i]);
    i++;
}
1
2
3
4
5

πŸ”‚ Using do-while Loop

int[] arr = {5, 10, 15};
int i = 0;

do {
    System.out.println(arr[i]);
    i++;
} while(i < arr.length);
5
10
15

🧾 Using for-each Loop (Enhanced For Loop)

This is the most concise and readable way to traverse arrays when index isn't needed.

int[] arr = {7, 14, 21, 28};

for(int num : arr) {
    System.out.println(num);
}
7
14
21
28

πŸ“Œ Note: for-each cannot be used if you need the index or to modify specific elements.


🧠 When to Use What?

Loop Type

Use Case

for loop

When you need index or modifying

while loop

When you use external conditions

do-while

When loop must run at least once

for-each

For read-only access