Loops in Java

Basic loops in Java are the following:

  • While loop
  • Do-While loop
  • For loop

While Loop

Condition checked at loop start. Depending on the condition, the loop body may never run.

int someValue = 4;
int factorial = 1;

while(someValue > 1) {
  factorial *= someValue;
  someValue--;
}
System.out.println(factorial) // 24

Do-while Loop

Condition continues running as long as the control condition is true, like the while loop above.

The key difference is the condition is checked at the end of the loop.

int iVal = 5;

do {
  System.out.print(iVal);
  System.out.print(" * 2 = ");
  iVal *= 2;
  System.out.println(iVal);
} while(iVal < 25);

For Loop

Check the condition at the loop start. Loop body may never run. For loop is very similar to while loop. The key difference is it provides simplified notation for loop control values: inside the for statement itself we can define the initialization work, write the condition followed by the update work. In a word: for (initialize; condition; update).

for(int i = 1; i < 100 ; i *= 2)
  System.out.println(i);

By comparison, the same code using a while loop would look like the following:

int i = 1;

while(i < 100) {
  System.out.println(i);
  i *= 2;
}

For-each Loop

A shorthand of For loop can be found with For-each loop. In this case, the loop executes a statement once for each array member. The loop handles collection length and accessing each value.

int[] values = { 10, 20, 15  }
int sum = 0;

for (int currentVal : values)
  sum += currentVal;

System.out.println(sum); // 45