What is for statement?
A for loop statement is an iteration statement.
The general form of a for-loop statement is
for (initialization; condition-expression; expression-list)
Statement
The initialization, condition-expression, and expression-list are separated by a semicolon.
A for-loop statement consists of four parts:
- Initialization
- Condition-expression
- Statement
- Expression-list
For example, the following for-loop statement will print all integers between 1 and 10, inclusive:
for(int num = 1; num <= 10; num++)
System.out.println(num);
Demo
public class Main {
public static void main(String[] args) {
for (int num = 1; num <= 10; num++)
System.out.println(num);/*from w w w.ja va2 s .c o m*/
}
}
Result
- First, int num = 1 is executed.
- Variables declared in the initialization part of the for-loop statement can only be used within that for-loop statement.
- Then, condition-expression (num <= 10) is evaluated, which is 1 <= 10.
- It evaluates to true for the first time.
- Then, the body of for-loop statement is executed, which prints the current value of num.
- Then, the expression in the expression-list, num++, is evaluated, which increments the value of num by 1 .
- Now, the value of num becomes 2.
- Then the condition-expression 2 <= 10 is evaluated, which returns true.
- Then the current value of num is printed.
- This process continues until the value of num becomes 10.
- Then, num++ sets the value of num to 11, and the condition-expression 11 <= 10 returns false
- Then, the execution of the for-loop statement stops.
Related Topics
Quiz
Example