In Java, the for
keyword is used to create a loop that executes a block of code multiple times. The for
loop has a specific syntax that allows you to specify the loop variable, the loop condition, and the loop increment or decrement.
Here's an example of how to use the for
loop in Java:
public class Main { public static void main(String[] args) { // Count from 1 to 10 for (int i = 1; i <= 10; i++) { System.out.println(i); } } }
This code creates a for
loop that starts at 1, continues until it reaches 10, and increments the loop variable i
by 1 on each iteration. The loop variable i
is initialized to 1 before the loop starts, and the loop condition i <= 10
is checked before each iteration. If the condition is true, the loop continues; if the condition is false, the loop ends.
The for
loop is a useful tool for performing a set of actions a specific number of times, or for iterating over the items in an array or other collection.