java
  1. java-for-loop

Java For Loop

Syntax

for (initialization; condition; increment/decrement) {
  // code block to be executed
}

Example

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

Output

0
1
2
3
4

Explanation

The for loop is one of the basic constructs in Java programming. It provides a way to iterate over a sequence of elements, executing a block of code for each iteration.

The for loop has three components:

  • Initialization: Set the initial value of the loop variable.
  • Condition: Check if the loop is still valid, based on the loop variable.
  • Increment/Decrement: Update the loop variable for the next iteration.

The for loop executes the block of code as long as the condition is true. Once the condition becomes false, the loop terminates.

In the example above, the initialization sets the loop variable i to 0. The condition checks if i is less than 5, and the increment updates i for each iteration. The code block inside the loop simply prints the value of i.

Use

The for loop is used in Java programs to iterate over various data structures, such as arrays and lists. It can also be used for other repetitive tasks, such as generating a sequence of numbers or performing a batch operation.

Important Points

  • The for loop is a basic construct in Java programming.
  • It iterates over a sequence of elements, executing a block of code for each iteration.
  • The loop has three components: initialization, condition, and increment/decrement.
  • The loop executes the block of code as long as the condition is true.
  • The loop is commonly used to iterate over arrays and lists.

Summary

The for loop is a fundamental construct in Java programming that allows for iteration over a sequence of elements. It has three components: initialization, condition, and increment/decrement. The loop executes the block of code as long as the condition is true and is commonly used to iterate over arrays and lists.

Published on: