Java Arrays Loop

🔁 Java Arrays Loop

In Java, arrays are often processed using loops. This allows you to access, modify, and iterate through elements efficiently. You can use for, for-each, and while loops with arrays.


1. Using for Loop

Classic way to loop through an array using index.

public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
}
}

📌 Output:

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

2. Using for-each Loop

Simpler way to loop through all elements.

public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange"};

for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

📌 Output:

Apple
Banana
Orange

3. Using while Loop

You can also loop through arrays with while.

public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int i = 0;

while (i < numbers.length) {
System.out.println(numbers[i]);
i++;
}
}
}

📌 Output:

1
2
3
4
5

4. Using do...while Loop

Executes the loop at least once.

public class Main {
public static void main(String[] args) {
int[] numbers = {100, 200, 300};
int i = 0;

do {
System.out.println(numbers[i]);
i++;
} while (i < numbers.length);
}
}

📌 Output:

100
200
300

5. Sum of Array Elements

public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;

for (int num : numbers) {
sum += num;
}

System.out.println("Sum = " + sum);
}
}

📌 Output:

Sum = 150

6. Find Maximum Value in Array

public class Main {
public static void main(String[] args) {
int[] numbers = {10, 25, 5, 40, 30};
int max = numbers[0];

for (int num : numbers) {
if (num > max) {
max = num;
}
}

System.out.println("Maximum value = " + max);
}
}

📌 Output:

Maximum value = 40

🧠 Summary

Loop Type Use Case
for Known indices, flexible
for-each Simpler, read-only iteration
while Conditional iteration
do...while Executes at least once

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *