Loops in java are control structure which allow a set of instructions or a block of code to be executed multiple times based on a specific condition . Loops are essential for tasks which requires iteration , such as performing an action a certain number of times or processing elements in an array.
There are three main types of loops in Java:
Example:
for ( int i=0 ; i<7; i++ ) {
System.out.println(“Iteration inside for loop ” + i);
}
- while loop : while loop in java is used when number of iteration is not known. The while loop continues as long as the specified condition remains true . In while loop, the condition is checked before each iteration .
Learn more about while loop…
Example:
int count = 0;
while ( count < 5 ) {
System.out.println ( “Count : “ +count);
count++;
}
- do-while loop : do-while loop is similar to while loop , but in do-while loop the code block is executed at least once and then the condition is checked after each iteration . Learn more about do-while Loop…
Example:
int count=0;
do {
System.out.println(“Count : “ +count);
count++;
} while ( count <3 );
Additionally , Java provides enhanced for loop ( for-each loop ) for iterating over arrays and collections .
Example :
String employess[ ]={ “Joy” , “Mic” , “William”};
for ( String employee : employees ) {
System.out.println(“Employee:”+employee);
}
Comparision table of for loop , while loop , do-while loop and for-each loop :
| Loop Type | When to use | Condition Checking | Executes atleast once? |
|---|---|---|---|
| For Loop | for loop is used in java when you want exact iterations | In for loop , condition is checked before loop body which is also called Entry-controlled . | no |
| while loop | while loop is used in java when you need condition check first. | In while loop , condition is checked before loop body which is called Entry-controlled. | no |
| do-while loop | do-while loop is used in java when you need the block of code to be executed atleast once before the condition is checked . | In do-while loop , condition is checked after loop body which is called Exit-controlled . | Yes |
| for-each loop | for-each loop in java is used when you process all collection items. | In for-each loop, condition is internally handled. | no |
RELATED ARTICLES:
