Java For Loop — Java Technical Interview Questions & Answers

Java For Loop

Java For Loop

  • for is the loop you use when you already know how many times to repeat. Shape: for (start; condition; update) { body }. Example: for (int i = 1; i <= 5; i++) print i.
  • Start runs once. Condition is checked before each round. Update runs after each body — usually i++. Trace i on paper: 1, 2, 3, 4, 5. Then code.
  • Classic work: print 1 to n, sum numbers, walk an array by index. The usual bug is off-by-one: i < n vs i <= n. Say the last value of i before you type.
  • Let's take this on the board with one tiny Main class — no extra files. Java For Loop — output: 1 then 2 then 3 then 4 then 5 — each on a new line. Start from main, go line by line, and stop at each print. That output is the proof for For Loop.
  i = 1
    │ i <= 5 ?
    ▼ yes
  body → i++ → check again
    │ no
    ▼
   stop

Technical Interview Tip: Trace i = 1 to 5 out loud, then write the loop.

Code Examples for Java For Loop

Example

// Java For Loop
public class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
      System.out.println(i);
    }
  }
}

Java For Loop — output: 1 then 2 then 3 then 4 then 5 — each on a new line.

How to Explain Java For Loop to an Interviewer

When is for the best loop?

When the count is known

What are the three parts of for?

init condition update

When does update run?

After each body

What is off-by-one?

i < n vs i <= n One extra or one missing round