When should you use a for loop, a while loop and a do-while loop in Java, and how do you choose between them?
Choose on the basis of what you know before the loop starts. A for loop is for the case where the number of iterations is known or bounded by a counter: the initialisation, the condition and the update all sit together in one place, so a reader sees the whole control structure at a glance. A while loop is for the case where the loop continues until some condition becomes false and you cannot predict how many times that takes — reading records until the stream is exhausted, retrying until a service responds.
A do-while differs from while in exactly one respect: the body always runs at least once, because the condition is tested after the body rather than before it. That is the right shape for input validation, where you must ask the user a question before you know whether to keep asking, and for retry loops where the first attempt is always worth making. Using a plain while loop for that case means duplicating the body or adding an artificial first-iteration flag.
Two extra loops complete the picture. The enhanced for loop, for (T item : collection), removes index bookkeeping entirely and is the clearest way to walk a collection; the trade-off is that you cannot skip ahead, and you must use the index form if you need to modify the collection while iterating. The stream forEach also covers the common case of applying an action to every element.
A practical rule: if you know the count, use for. If the condition alone decides, use while. If the body must run at least once, use do-while. If you are walking a collection, use the enhanced for.