A loop statement allows us to execute a statement or group of statements multiple times
Loop & Description
- while loop: Repeats a statement while a given condition is true.
- for loop: Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
- do…while loop: it tests the condition at the end of the loop body.
Enhanced for loop in Java
Used to traverse collection of elements including arrays:
for(declaration : expression) { // Statements }
- Declaration: The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
- Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
Example:
public class Test { public static void main(String args[]) { int [] numbers = {5, 8, 7, 4, 9}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names = {"Tiger", "Puss", "Smokey", "Misty"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }
Output:
5,8,7,4,9, Tiger,Puss,Smokey,Misty
Loop Control Statements
When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Java supports the following control statements.
- Break statement: Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
- continue statement: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.