Java For Loop


Java For Loop

If you know exactly how many times you want to enter a code block, use a for loop instead of a while loop:


Syntax
for (statement 1; statement 2; statement 3) {
            // code block to be executed
          }

Statement 1 was made (one time) prior to the creation of the code block.

Statement 2 explains the condition of using the code block.

Statement 3 is made (always) after the code was issued.

The example below will print numbers 0 to 4:


Example
for (int i = 0; i < 5; i++) {
            System.out.println(i);
          }
          

Example explained

Statement 1 sets the variable before the loop starts (int i = 0).

Statement 2 sets the condition for the loop to work (I must be under 5). If the condition is correct, the loop will restart, if false, the loop will end.

Statement 3 increases the value (i ++) each time a code block in a loop is generated.


Another Example

This example will only print equal values ​​between 0 and 10:


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


For-Each Loop

There is also a "for-each" loop, used specifically to combine elements in an array:


Syntax
for (type variableName : arrayName) {
            // code block to be executed
          }
          

The following example removes all features from the array of cars, using the "for-each" loop:


Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
            for (String i : cars) {
              System.out.println(i);
            }