Home Loops

On looping

Java lets you "loop" through values in several different ways. Though many of these looping constructs are, to a certain extent, mechanically interchangeable, they each have a different meaning and use. Which looping construct you use will imply multiple things about your code. Use the one that best fits your overarching intent.

In CSE 142, we learn about for loops and while loops. Note that other kinds of loops such as foreach loops are first introduced in CSE 143, count as advanced material in CSE 142, and so should not be used.

For loops

Use a for loops when you know exactly how many times you need to loop before entering the loop. Do not use loops when you end up always looping only once.

While loops

Use a while loops when you do NOT know exactly how many times you need to loop, and can only find out in the middle of looping – when you need a potentially infinite or indefinite loop.

Do-while loops

We do not expect you to know about or use do-while loops in CSE 14x – consider them optional material. You may use do-while loops once we have taught you about regular while loops, if you wish.