Java for Loop

www.igif‮edit‬a.com

In Java, the for loop is used to execute a block of code repeatedly for a specific number of times. It's a type of loop that allows you to specify the number of iterations.

Here is the basic syntax of the for loop in Java:

for (initialization; condition; update) {
    // code to execute for each iteration
}

The for loop has three parts:

  • Initialization: This is the code that is executed once before the loop starts. It's used to declare and initialize loop variables.
  • Condition: This is the test that is performed at the beginning of each iteration. The loop continues as long as this condition is true.
  • Update: This is the code that is executed at the end of each iteration. It's used to update the loop variables.

Here is an example that uses the for loop to print the numbers from 1 to 10:

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

In this example, the loop starts with i being initialized to 1. The loop continues as long as i is less than or equal to 10. After each iteration, the value of i is incremented by 1. The loop prints the value of i for each iteration, resulting in the numbers 1 to 10 being printed to the console.

You can also use the for loop to iterate over arrays, collections, and other data structures in Java. For example, you can use the following for loop to iterate over an array of strings:

String[] names = {"Alice", "Bob", "Charlie"};

for (int i = 0; i < names.length; i++) {
    System.out.println(names[i]);
}

In this example, the loop starts with i being initialized to 0. The loop continues as long as i is less than the length of the names array. After each iteration, the value of i is incremented by 1. The loop prints each element of the names array for each iteration, resulting in the names "Alice", "Bob", and "Charlie" being printed to the console.