Sobes.tech
Junior

How do loops in Java differ?

sobes.tech AI

Answer from AI

In Java, there are several types of loops, each designed for specific tasks:

  • for: Used when the number of iterations is known in advance.
  • while: Executes as long as the condition is true. The number of iterations is not known beforehand.
  • do-while: Similar to while, but the code block executes at least once before the condition is checked.
  • Enhanced for (for-each): Convenient for iterating over elements of arrays and collections without explicitly managing the index.

Here is a table with key differences:

Feature for while do-while Enhanced for
Is the number of iterations known? Usually yes No No Depends on the size of the collection/array
Condition check Before the first iteration Before the first iteration After the first iteration Implicit
Syntax for (init; cond; update) while (condition) do { ... } while (condition); for (type element : collection)
Index management Explicit (usually) Implicit or explicit Implicit or explicit Not present
Suitable for Fixed number of repetitions Unknown number of repetitions before execution At least one execution, then based on condition Iterating over collection/array elements

Code examples:

// for loop
for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

// while loop
int count = 0;
while (count < 3) {
    System.out.println("While count: " + count);
    count++;
}

// do-while loop
int doCount = 0;
do {
    System.out.println("Do-While count: " + doCount);
    doCount++;
} while (doCount < 2);

// enhanced for
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println("Number: " + number);
}

The choice of a specific loop depends on the logic of the task and whether the number of iterations is known in advance.

How do loops in Java differ? — Java - sobes.tech