Java Notes

Loop Idioms

Loops are often used to accomplish the same kinds of tasks, so many loops tend to be one of several common styles.

Loop reading input

It's very common to read input in a loop: read a value, process it, go back to read another, etc. Many beginning programs have this structure for reading input from the user. When a standard GUI (Graphical User Interface) is used, loops are not used, but loops are still used to read from files or over the internet.

Loop a fixed number of times

Sometimes you just want to do something a fixed number of times.

Loop over a String using an index

A common problem is move sequentially over each character position in a string to look for something, or to get the character and do something.

Loop over an array with an index

Loop over a data structure - using iterator

Loop over a data structure - using for-each