Using Loops


  • A basic for statement has three parts: declaration and/or initialization, boolean evaluation, and the iteration expression.
  • If a variable is incremented or evaluated within a basic for loop, it must be declared before the loop, or within the for loop declaration.
  • A variable declared (not just initialized) within the basic for loop declaration cannot be accessed outside the for loop (in other words, code below the for loop won't be able to use the variable).
  • You can initialize more than one variable of the same type in the first part of the basic for loop declaration; each initialization must be separated by a comma.
  • An enhanced for statement (new as of Java 6), has two parts, the declaration and the expression. It is used only to loop through arrays or collections.
  • With an enhanced for, the expression is the array or collection through which you want to loop.
  • With an enhanced for, the declaration is the block variable, whose type is compatible with the elements of the array or collection, and that variable contains the value of the element for the given iteration.
  • You cannot use a number (old C-style language construct) or anything that does not evaluate to a boolean value as a condition for an if statement or looping construct. You can't, for example, say if(x), unless x is a boolean variable.
  • The do loop will enter the body of the loop at least once, even if the test condition is not met.