The for loop in Java is utilized to repeatedly execute a specific part of a program. It offers a convenient way to iterate a block of code multiple times. When the number of iterations is predetermined or fixed, the for loop is recommended for its concise and efficient syntax.
There are three types of (for loops) in Java.
- Simple for loop
- For-each or Enhanced for Loop
- Labeled for Loop
Simple for Loop in Java:
A basic for loop in Java follows a similar structure as in C/C++. It includes four essential components: variable initialization, condition checking, and incrementing or decrementing the value. These parts work together to control the loop’s execution.
Initialization: The initialization is an initial condition that is executed once at the beginning of the loop. It can involve initializing a variable or using an already initialized variable. This step is optional.
Condition: The condition is evaluated each time to test if the loop should continue executing. It determines whether the loop’s execution should continue or not. The condition must return a boolean value, either true or false. This step is optional.
Increment/Decrement: The increment or decrement operation modifies the value of the variable after each iteration of the loop. It allows for controlling the loop’s iteration and progression. This step is optional.
Statement: The statement within the loop is executed repeatedly until the condition evaluates to false. It defines the actions or operations to be performed during each iteration of the loop.
Syntax: