Repeat

For Loop

Java

 

For loop

Java 8
for (int count=5; count>0; count--) {
  
    System.out.println(count);
  
}

for statement is a handy syntax for iterating through arrays and iteratable objects. Below is the most common syntax used:

for (<initialize>; <condition>; <modification>) {
    <code block>
}

The for loop above executes in the order below:

  1. Execute <initialize>
  2. If <condition> evaluates to true execute the <code block>
  3. Execute <modification>
  4. Go to Step 2

This will print 5 4 3 2 1 on Console.

 

Single For loop Statement

Java 8
for (int count=5; count>0; count--)
    System.out.println(count);

If you only have one statement in your for block, you can drop the curly braces { }.

This will print 5 4 3 2 1 on Console.

 

ForEach loop

Java 8
String[] animals = {"Cat", "Dog", "Cow"};

for (String animal : animals) {
    System.out.println(animal);
}

This form of for is used to iterate through arrays and collections.

This will print Cat Dog Cow on Console.