Loading...

Java for-each

Store three whole numbers in an array named slots: 2, then 4, then 6. Write for (int n : slots) and print n inside the braces. The screen should show three lines: 2, then 4, then 6. You do not write an index counter on this page. Each pass hands the next value from the array to the name n. That walk is what this page teaches.

One name for each value in the array

Create a small program file named Pack.java. The public class on the first line must match the file name: public class Pack. Do not leave an older Skip or Pulse class name in this file; the compiler expects the class name and the file name to agree.
Inside main, store the array first:
int[] slots = {2, 4, 6};
That line does not print. It only keeps three whole numbers under the name slots. Then the for-each loop:
for (int n : slots) {
System.out.println(n);
}
The word for is still lowercase. Inside the parentheses sit three pieces with a colon in the middle: the type int, the name n for one element, then a colon, then the array name slots. That colon is not a case label and not a path separator. It marks “each value from slots goes into n.” The braces hold the body. System.out.println(n); writes the current value with no quotes around n. Save the file before you compile.

Program that prints 2 then 4 then 6

This is the version you compile first.

int array walk

java
public class Pack {
    public static void main(String[] args) {
        int[] slots = {2, 4, 6};
        for (int n : slots) {
            System.out.println(n);
        }
    }
}

From the folder that holds Pack.java, run javac Pack.java. When the parentheses, braces, and colons match, javac writes no line of its own. Then run java Pack — not java Pack.java. Leave the .java ending off the second command. The same two commands work on Windows and on macOS; this page does not need a different shell spelling for either system. The program should print three lines and stop: 2, then 4, then 6. It should not ask you to type. If the terminal waits for keyboard input, a nextLine call from an older exercise is still in the file. Delete that call and keep the array plus the for-each above. A wrong screen line does not mean you need a new JDK install.

Walk one full run in order. slots holds 2, then 4, then 6. The first pass sets n to 2 and println writes 2. The second pass sets n to 4 and writes 4. The third pass sets n to 6 and writes 6. Then there are no more values, so the loop ends. You did not write int i = 0 or i < slots.length on this page. The for-each header asks Java to visit each stored value once. The name n is new on every pass only in the sense that it holds the next element; you still declare it once in the header as int n.

Walk a String array the same way

Change the stored array and the element type so each value is a short word:
String[] tags = {"red", "blue"};
for (String t : tags) {
System.out.println(t);
}
Now the screen should show two lines: red, then blue. The colon still sits between the element type and the array name. The body still prints the name that holds one element.

String array walk

java
public class Pack {
    public static void main(String[] args) {
        String[] tags = {"red", "blue"};
        for (String t : tags) {
            System.out.println(t);
        }
    }
}

Compile and run again: javac Pack.java, then java Pack. You should see two lines. You replaced the int array with a String array and matched the element name’s type to String. After you have seen red and blue, you can put the int demo back. Both versions are valid Java. They teach the same for-each shape with different element kinds.

Read the String run once more. tags holds red, then blue. The first pass sets t to red and prints it. The second pass sets t to blue and prints it. Then the loop ends. Quotes in the array literal mark the text stored in the array. println(t) without extra quotes around t writes those stored letters to the screen.

Rules that keep for-each clear

The parentheses must hold type, name, colon, and array name in that order. Writing for (int n slots) without the colon makes javac fail. The element type must fit the array: int with an int array, String with a String array. Putting int n beside a String[] array is not the shape this lesson compiles. Braces still hold the body when the body has one or more lines.

for-each is not the counted for from the Beat page, and it is not break from the Skip page. The counted for wrote start, test, and step with a counter. for-each walks values already stored in an array. break ends a loop early; this page’s first demo prints every value. Do not leave a Skip break demo or a Pulse while in the same main and wonder why the screen shows 1 and 2 instead of 2, 4, 6. This session’s main should hold the array and the for-each only.

A common mix-up is printing the syntax itself: System.out.println("for (int n : slots)");. That writes the characters of the header. It does not walk the array. Another mix-up is System.out.println("n"); with quotes, which prints the letter n on every pass instead of 2, 4, and 6. Keep println(n) without quotes when you want the element value on the screen.

If the array has no elements — for example int[] slots = {}; — the body never runs and the screen stays blank. That is still a valid for-each; this lesson’s demos keep at least two values so you can see the printed lines. When you later need an index number on the screen, the counted for returns; for-each is for visiting values without managing that index yourself. Changing a value inside the loop with n = 9; does not rewrite the array slot on this beginner shape — treat n as the value you read for printing, not as a tool for editing slots.

What you can do now

You can store an array, write for (Type name : arrayName), and print each value once. Matching the element type to the array keeps the loop compiling. The next page is methods, where you group lines under a name you can call from main.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top