+91 81900 98289

Java For Loop

A for loop is a compact while for counting. The three parts in parentheses are the start, the test, and the update. for (int i = 0; i < 3; i++) creates i, continues while i is below 3, and adds 1 after each pass.

for-each walks every item in an array or another iterable. Use it when you need the value and not the index. Use the counted for when you also need the position.

Example

The colon form visits each string in the array once, from the first item to the last.

public class Loop { public static void main(String[] args) { String[] skills = {"Java", "SQL", "Git"}; for (String skill : skills) { System.out.println(skill); } } }
i++ is the same as i = i + 1 when i is a plain number. The update runs after the body, not before the first test.