# Java: Loops - 'while' and 'for'

## Purpose

The purpose of loop statements is to repeat Java statements many times. There are several kinds of loop statements in Java.

while statement - Test at beginning
  The while statement is used to repeat a block of statements while some condition is true. The condition had better become false somewhere in the loop, otherwise it will never terminate.

      int i = 0;
      while {i < names.length) (
          System.out.println(names[i]);
          i++;
      }

for statement - traditional three part
  If you want to repeat a block of statements a fixed number of times, the for loop is the right choice. It's alos used in many other cases where there the intitialization of a loop, the loop condition, and the loop increment can be combined.

      for (int i = 0; i < names.length; i++) (
          System.out.println(names[i]);
      }

do..while statement - Test at end
  When you want to test at the end to see whether something should be repeated, the do..while statement is the natural choice.

      do (
          . . .
          String ans = JOptionPane.showInputDialog(null, "Do it again (Y/N)?");
      } while (ans.equals("Y"));

for statement - Java 5 data structure iterator
  Java 5 introduced what is sometimes called a "for each" statement that accesses each successive element of an array, List, or Set without the bookkeeping associated with iterators or indexing.

      for (String s : names) (
          System.out.println(s);
      }

## Similar to the 'if' statement

There are three general ideas that you will see in many parts of Java.

- use of braces `{}` to enclose multiple statements.
- indentation
- boolean (true/false) conditions.

## Scope of loop indicated with braces {}

If the body of a loop has more than one statement, you must put the statements inside braces. If there is only one statement, it is not necessary to use braces `{}`. However, many programmers think it is a good idea to always use braces to indicate the scope of statements. Always using braces allows the reader to relax and not worry about the special single statement case.

## Indentation of loops

All statements inside a loop should be indented 2-4 spaces (the same as an `if` statement.

## boolean true/false conditions

True/false (boolean) expressions control both loops and the if statement.