Previous | Home | Next |
A do while loop is a control flow statement that executes a block of code at least once, then repeatedly executes the block, or not, depending on a given Boolean condition at the end of the block. First the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop.
syntax :
do { statements ; increment /decrement; } while(condition);
Example :
class DoWhile { public static void main(String args[]) { int i,n=5; i=1; do { System.out.println(i); i++; }while(i<=n); } }
output :
1 2 3 4 5
The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
Syntax :
for(data_type variable : array | collection) { //statements }
Example :
class ForEachExample { public static void main(String args[]) { int arr[]={12,13,14,44}; for(int i:arr) { System.out.println(i); } } }
output :
12 13 14 44
Previous | Home | Next |