Loading...

Java for Loops

Run a small loop that starts n at 1, keeps going while n is less than or equal to 3, and adds 1 to n after each pass. Inside the braces, print n. The screen should show three lines: 1, then 2, then 3. That repeating print is what this page teaches.

Three parts sit in the for line

Create a small program file named Beat.java. The public class on the first line must match the file name: public class Beat. Do not leave an older Dial or Gate class name in this file; the compiler expects the class name and the file name to agree.
Inside main, write the loop before any leftover switch or if:
for (int n = 1; n <= 3; n = n + 1) {
System.out.println(n);
}
The word for is lowercase. Inside the parentheses sit three jobs, separated by semicolons. First: int n = 1; — make a whole-number name n and start it at 1. Second: n <= 3 — keep going while that test is true. Third: n = n + 1 — after each pass through the braces, store one more under n. The braces hold the body. System.out.println(n); writes the current value of n and ends the line. There are no quotes around n on that writing line, so the number appears, not the letter n. Save the file before you compile.

Program that prints 1 then 2 then 3

This is the version you compile first.

n from 1 to 3

java
public class Beat {
    public static void main(String[] args) {
        for (int n = 1; n <= 3; n = n + 1) {
            System.out.println(n);
        }
    }
}

From the folder that holds Beat.java, run javac Beat.java. When the parentheses, braces, and semicolons match, javac writes no line of its own. Then run java Beat — not java Beat.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: 1 on the first line, 2 on the second, 3 on the third. 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 for loop above. A wrong screen line does not mean you need a new JDK install.

Walk one full run in order. n starts at 1. The test n <= 3 is true, so the body runs and println(n) writes 1. Then the step n = n + 1 stores 2. The test is still true, so the body writes 2. The step stores 3. The test is still true, so the body writes 3. The step stores 4. Now n <= 3 is false, so the loop ends. Nothing else prints. You do not write three separate println lines by hand; the same body runs three times with a changing n. The start runs once at the beginning. The test runs before each pass. The step runs after each pass. Those three jobs stay in the parentheses; the writing job stays in the braces.

Raise the upper bound

Change only the test so the loop goes farther:
for (int n = 1; n <= 5; n = n + 1) {
System.out.println(n);
}
Leave the start and the step as they are. Now the screen should show five lines: 1, 2, 3, 4, and 5.

n from 1 to 5

java
public class Beat {
    public static void main(String[] args) {
        for (int n = 1; n <= 5; n = n + 1) {
            System.out.println(n);
        }
    }
}

Compile and run again: javac Beat.java, then java Beat. You should see five lines. You did not rewrite the println — only the test inside the for parentheses changed. After you have seen five lines, you can put n <= 3 back to return to the first demo. Both versions are valid Java. They teach the same for shape with a different stopping point.

Read the five-line run once more. n starts at 1. Each true test prints the current n and then adds 1. When n becomes 6, the test fails and the loop stops. The digit 6 never appears on the screen in this demo, because the body only runs while the test is still true.

Rules that keep the loop clear

Parentheses around the three parts are required. Writing for int n = 1; n <= 3; n = n + 1 { … } without the outer parentheses makes javac fail. Semicolons separate the three parts inside those parentheses. The body on this page always sits in braces. Java allows a one-line body without braces, but a second line under the for stays outside the loop unless braces wrap both lines. Keep braces in both demos so the body is obvious.

for is not switch and not if. switch (choice) picks among fixed case labels once. if (ready) chooses one of two paths from true or false. for repeats the same braced body while a counter moves. Do not leave a Dial switch or a Gate if in the same main and wonder why the screen shows mid or pass instead of 1, 2, 3. This session’s main should hold the for loop only.

A common mix-up is printing the syntax itself: System.out.println("for (int n = 1; n <= 3; n = n + 1)");. That writes the characters of the for header. It does not repeat. Another mix-up is putting quotes around n in the body: System.out.println("n"); writes the letter n on every pass, not the changing number. Keep println(n) without quotes when you want the counter on the screen.

The step n = n + 1 can also be written n++ in later code you will see elsewhere. This page keeps n = n + 1 so every mark on the line is a word or number you already know how to read. The start can begin at 0 instead of 1 when a lesson needs that; here both demos start at 1 so the first printed line matches the first count people say out loud. If the test is already false at the start — for example n starts at 1 and the test says n <= 0 — the body never runs and the screen stays blank. That is still a valid for; this lesson’s demos keep a test that is true at least once so you can see the printed lines.

What you can do now

You can write a for with a start, a test, and a step, put a println in the braces, and watch the counter appear on successive lines. Changing the test changes how many lines you get. The next page is while, where the test sits in its own place and the step is written inside the body instead of inside the for parentheses.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

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

❓
5
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