Java Lab Documentation

for Loops

Category:Control Structures

A for loop allows you to repeat blocks of code for a specified duration. You can have a block of code repeat a specific number of times or repeat until a specified condition is met. The for loop syntax has three key components:

  • initialExpression: This part of the loop syntax initializes the variable that will be used to determine how many times the loop is executed. The initialExpression part is only executed once.

  • condition: This is the condition for determining whether or not to execute the code in the body of the loop (similar to an if statement condition). If condition evaluates to true, the body of the for loop executes.

  • updateExpression: This part of the expression updates the variable initialized in the initialExpression. The condition is then evaluated again to see if the condition is still true with the updated value of the variable.

Examples

Performing a Set Number of Actions

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

Output:

0

1

2

3

4

Traversing an Array

A for loop can be used to traverse arrays and ArrayLists.

int[] numbers = { 1, 2, 3, 4 };

for(int index =0; index < numbers.length; index++) {
   System.out.println(numbers[index]);
}

Output:

1

2

3

4

Syntax

for (initialExpression; condition; updateExpression) {
   // body of code
}