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

Answer from DevilsHnd - 退した on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_arrays_loop.asp
Java Loop Through an Array
Java Examples Java Videos Java ... can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run....
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);

Discussions

Struggling with Arrays and loops

Why is it a matrix rather than a 1D array? It has a width of 1, so it is linear. Do you want to add more students to the same grade? Then width should be more than 1 (or grow as you add students).

You can put fullname into the correct place in your array without conditionals using:

currentGrade[studentAge - 5] = fullName; //check for valid input, first.

More on reddit.com
🌐 r/learnjava
5
1
November 6, 2021
create new array inside loop? - Processing Forum
I need to create a new Array inside for loop for each iteration... ... You done stuff with ActionScript previously? That looks very much like stuff I'd write working with MovieClips; but it's not going to work in Java: IIRC it's not possible to construct an variable name dynamically like that ... More on forum.processing.org
🌐 forum.processing.org
October 20, 2010
Java array/for loop
post your code. More on reddit.com
🌐 r/AskProgramming
5
2
September 19, 2016
For-each loop ArrayList
Java has something called autoboxing and unboxing . Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer. In the examples above the List contains Integer objects. The difference is: In the first, val is a reference to the Integer object in the List. In the second, val is a primitive value that was unboxed from the Integer object in the List. More on reddit.com
🌐 r/learnjava
6
11
April 4, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterating-arrays-java
Java - Loop Through an Array - GeeksforGeeks
December 2, 2024 - Example 3: We can also loop through an array using while loop. Although there is not much of a difference in for and while loop in this condition. While loop is considered effective when the increment of the value depends upon some of the condition. ... // Java program to iterate over an array // using while loop import java.io.*; class Main { public static void main(String args[]) { // taking an array int a[] = { 1, 2, 3, 4, 5 }; int i = 0; // Iterating over an array // using while loop while (i < a.length) { // accessing each element of array System.out.print(a[i] + " "); i++; } } }
🌐
CodingBat
codingbat.com › doc › java-array-loops.html
CodingBat Java Arrays and Loops
In contrast, Java Lists can grow and shrink over time -- this is a big feature that Lists have that arrays do not. The length of an array can be accessed as a special ".length" attribute. For example, with the above "values" array, we can access the size of the array as "values.length". It is common to use a 0...length-1 for-loop to iterate over all the elements in array:
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit7-Arrays › topic-7-3-arrays-with-foreach.html
7.3. Enhanced For-Loop (For-Each) for Arrays — CS Java
To set up a for-each loop, use for (type variable : arrayname) where the type is the type for elements in the array, and read it as “for each variable value in arrayname”. for (type item: array) { //statements using item; } See the examples below in Java that loop through an int and a String ...
🌐
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
It loops from the middle to the end doubling each value. Since there are 6 elements it will start at index 3. ... This would be true if array elements didn't change, but they do. Wait a minute! In Unit 5 we discussed Java parameter passing and pass by value, in which the actual argument value is copied into the formal parameter variable.
Find elsewhere
🌐
Programiz
programiz.com › java-programming › enhanced-for-loop
Java for-each Loop (With Examples)
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
🌐
JustAnswer
justanswer.com › computer-programming › oc1au-trying-use-loop-parallel-array.html
How to Use a For Loop with Parallel Arrays in Java - Expert Q&A
When using a for loop with parallel arrays, ensure both arrays have the same length to avoid out-of-bound errors. Use consistent indexing to access corresponding elements simultaneously.
🌐
W3Schools
w3schools.com › java › java_foreach_loop.asp
Java For-Each Loop
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other data structures):
🌐
Quora
quora.com › How-do-I-output-a-loop-to-a-list-or-array-in-Java
How to output a loop to a list or array in Java - Quora
Answer (1 of 4): I see no reason this would make sense. A loop is a sequence of code that repeats over and over. Why would you want to output those instructions to a list or an array? Perhaps you meant to ask, “How can I use a loop to compute a set of values which I will store in a list or array...
🌐
Reddit
reddit.com › r › learnjava › comments › qnjihn › struggling_with_arrays_and_loops
r/learnjava - Struggling with Arrays and loops
November 6, 2021 -

I'm relatively new to java and up until this point aside from a few 'normal' speed bumps, I've had a good grasp on the content we've been learning. However we're doing arrays now and the course content doesn't cover input, if else statements that assign strings to arrarys, or much other than the basics of 'int' 1D and 2D arrays.

I have to store a 'name' into a 'grade'. I've initialized all my variables as you can see, and the code blocks that aren't commented out work exactly as they're supposed to but I don't know if I'm on the right track with my logic or if 2D arrays are the right ones to use and then how to apply them appropriately?

Edited: Format

Code:

  1. static void enrolMethod(){

  2. Scanner input = new Scanner(System.in);

  3. String[][] currentGrade = new String [1][10];

  4. currentGrade[0][0] = "Grade_Prep:";

  5. currentGrade[1][0] = "Grade_1:";

  6. currentGrade[2][0] = "Grade_2:";

  7. currentGrade[3][0] = "Grade_3:";

  8. currentGrade[4][0] = "Grade_4:";

  9. currentGrade[5][0] = "Grade_5:";

  10. currentGrade[6][0] = "Grade_6:";

  11. String firstName;

  12. String n1;

  13. String lastName;

  14. String n2;

  15. String fullName;

  16. int studentAge;

  17. String enrolAgain;

  18. System.out.println("Enter child's first name:");

  19. firstName = input.nextLine();

  20. n1 = firstName.substring(0,1).toUpperCase() + firstName.substring(1);

  21. System.out.println("Enter child's surname:");

  22. lastName = input.nextLine();

  23. n2 = lastName.substring(0,1).toUpperCase() + lastName.substring(1);

  24. fullName = (n1 + "_" + n2);

  25. System.out.println("Enter child's age");

  26. studentAge = input.nextInt();

  27. //        //IF STATEMENTS FOR AGE HERE

  28. //        if (studentAge == 5) {

  29. //            currentGrade[0][0] = fullName;            

  30. //        } else if (studentAge == 6) {

  31. //            currentGrade[1][0] = fullName;

  32. //        } else if (studentAge == 7) {

  33. //            currentGrade[2][0] = fullName;

  34. //        } else if (studentAge == 8) {

  35. //            currentGrade[3][0] = fullName;

  36. //        } else if (studentAge == 9) {

  37. //            currentGrade[4][0] = fullName;

  38. //        } else if (studentAge == 10) {

  39. //            currentGrade[5][0] = fullName;

  40. //        } else if (studentAge == 11) {

  41. //            currentGrade[6][0] = fullName;

  42. //        } else {

  43. //            System.out.println("Invalid input. Please Try Again!");

  44. //            enrolMethod();

  45. //        }

  46. //STORE TO ARRAY HERE???

  47. System.out.println("This child has been successfully enrolled: " + fullName);

  48. System.out.println("Do you want to enrol another child? Y/N");

  49. enrolAgain = input.next();

  50. if (enrolAgain.equalsIgnoreCase("y")) {

  51. enrolMethod();

  52. } else if (enrolAgain.equalsIgnoreCase("n")) {

  53. menuSelect();

  54. }

  55. }

🌐
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 - I know we covered quite a few things ... been talking about. ... The enhanced for loop (also known as a foreach) loop in Java offers a simplified, error-resistant way to iterate over arrays and collections...
🌐
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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for...of
for...of - JavaScript | MDN
The for...of loop iterates and logs values that iterable, as an array (which is iterable), defines to be iterated over.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 305150 › array-and-for-loop
java - array and for loop | DaniWeb
August 18, 2010 - As @NormR1 noted, tabs are brittle — use formatted output so columns line up. Example (uses a short TCP connect as the reachability test; this avoids some of the platform/ICMP quirks of other approaches): import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Arrays; import java.util.List; public class CheckHosts { private static boolean canConnect(String host, int timeoutMs) { try (Socket s = new Socket()) { s.connect(new InetSocketAddress(host, 80), timeoutMs); return true; } catch (IOException e) { return false; } } public static void main(String[] args) { List<String> hosts = Arrays.asList("web1.local", "db01.local", "backup.local"); int timeout = 3000; System.out.printf("%-16s %s%n", "Server", "Up?"); for (String h : hosts) { System.out.printf("%-16s %b%n", h, canConnect(h, timeout)); } } }
🌐
DataCamp
datacamp.com › doc › java › java-for-loop
Java For Loop
The loop iterates through the numbers array, using the index i to access each element and print its value. public class NestedForLoopExample { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.println("i: " + i + ", j: " + j); } } } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
March 6, 2026 - Example 2: Iterating in a List using for-each loop ... import java.util.*; class Geeks { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(3); list.add(5); list.add(7); list.add(9); int max = Integer.MIN_VALUE; for (int num : list) { if (num > max) { max = num; } } System.out.println("List of Integers: " + list); System.out.println("Maximum element: " + max); } }
🌐
Processing Forum
forum.processing.org › one › topic › create-new-array-inside-loop.html
create new array inside loop? - Processing Forum
October 20, 2010 - The usual way - in Processing at least - to achieve what you describe is to use a container for the objects (in this case Arrays) being created inside the loop. You could do this with a 2D array but, depending on what you want to store, an ArrayList may be more flexible:
🌐
freeCodeCamp
freecodecamp.org › news › enhanced-for-loops-in-java-how-to-use-foreach-loops-on-arrays
Enhanced For Loops in Java – How to Use ForEach Loops on Arrays
February 17, 2023 - To loop through and print all the numbers in the array, we made use of a for-each loop: for(int number : even_numbers){...}.
🌐
GeeksforGeeks
geeksforgeeks.org › java › arrays-in-java
Arrays in Java - GeeksforGeeks
An integer array arr is declared and initialized in the main method. The sum() method is called with arr as an argument. Inside the sum() method, all array elements are added using a for loop.
Published   1 month ago