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

Example

Display the numbers from 0 to 4.

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

Definition and Usage

The for loop iterates through a block of code repeatedly for a specified number of times.

Based on the provided example:

  • The first statement initializes a variable before the loop commences (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 repeats; if false, the loop terminates.
  • Statement 3 increments a value (i++) after each execution of the code block within the loop.

More Examples

Additionally, there exists a “for-each” loop, primarily employed for traversing elements within an array:

The subsequent example demonstrates outputting all elements within the “cars” array using a “for-each” loop:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}