Loops
for, while, and where a loop has to end.
for is handy when the number of steps is known: an index, a range, walking an array. while fits when the end depends on a condition that changes inside. do-while runs the body at least once. A service hardly ever needs it, and it easily hides a first-step bug.
An infinite loop is usually a forgotten counter update or a condition that never becomes false. In the training sandbox such code hits the time limit and fails. In a service it holds a thread. A pooled thread that spins forever means an unreachable server while the process is still alive.
Walk a collection with for-each: for (String item : items). You only need an index if you change the list by position or read a neighbour. You must not remove from a list during for-each: you will get a ConcurrentModificationException. To remove, use an Iterator or removeIf.
A sum, a search and a filter are three different loops, not one "universal" one. If a loop holds five flags, extract a method. A loop should read like a single sentence: "for each order, add the price".
Practice
Which loop is shorter
You need to add the numbers from 1 to n, and n is known in advance. Which form is more direct here?
- for
- do-while
- recursion without a base case
- switch
Sum up to four
What is the sum of the integers from 1 to 4 inclusive?
Sum from 1 to n
Write static int sumTo(int n). Return the sum of the integers from 1 to n inclusive. For n less than 1, return 0.