Java - for loop Initialization

Introduction

The for-loop initialization statement can define variables of the same type.

It can have a list of expression statements separated by a comma.

Declares two variables i and j of the same type int

for(int i = 10, j = 20; ; );

Declares one double variable salary

for(double salary = 1234.56D; ; );

Attempts to declare two variables of different types

for(int i = 10, double d1 = 1234.5D; ; ); // An error

Uses an expression i++

int i = 100;
for(i++; ; );    // OK

Uses an expression to print a message on the console

for(System.out.println("Hello"); ; );  // OK

Uses two expressions: to print a message and to increment num

int num = 100;
for(System.out.println("Hello"), num++; ; );

You cannot re-declare a variable that is already in scope.

int i = 10;
for (int i = 0; ; ); // An error. Cannot re-declare i

You can reinitialize the variable i in the for-loop statement.

int i = 10; // Initialize i to 10
i = 500; // Value of i changes here to 500
for (i = 0; ; ); // Reinitialize i to zero inside the for-loop loop

Related Topic