Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

For Loop

Java For Loop

If you have a predetermined number of iterations for a block of code, opt for the for loop instead of a while loop.

Syntax

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed once before the code block is executed.

Statement 2 specifies the condition for executing the code block.

Statement 3 is executed after the code block has been executed, and it repeats every time.

The following example will print numbers from 0 to 4:

Example

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

Example explained

Statement 1 initializes a variable before the loop begins (int i = 0).

Statement 2 establishes the condition for the loop to execute (i must be less than 5). If the condition is true, the loop restarts; if false, the loop terminates.

Statement 3 increments a value (i++) each time the code block within the loop executes.

Another Example

This example specifically outputs only the even numbers within the range of 0 to 10.

Example

for (int i = 0; i <= 10; i = i + 2) {
  System.out.println(i);
}