A for loop in java is to iterate a code block, or in simple terms to run through a repetitive loop of some process with conditions, for loop is the best thing to go for in java programming language.
- It has a variable, conditions, and change.
- the variable is declared at the beginning as what it needs to be.
- Condition is given based upon the variable declared in the for loop.
- And lastly, the change is executed inevitable whether let it be increment or decrement it is up to you.
Syntax
for(variable; condition; change)
{
//code block
}
Example
public class Test
{
public static void main(String[] args)
{
for(int value = 15; value <= 20 ; value++)
{
System.out.println(value);
}
}
}
Output:
15
16
17
18
19
20
We have used the integer value as the variable and initialized it to 15. So that is where I am gonna begin with and I want the condition of up to 20 numbers from 15. So value <= 20 comes as the condition. Lastly, I wanna increment these numbers one by one during every loop iteration.