For, while, do-while, Enhanced for loop, Infinite loop - looping statements with examples in java


Looping statements in java >
    • 1.1) for,
      • Infinite for loop
      • Enhanced for loop
    • 1.2) while,
      • Infinite while loop
    • 1.3) do-while
      • Infinite do-while loop
Difference between while and do-while loop


Looping statements are Control Flow Statements. Control Flow Statements are statements inside your source files which are generally executed from top to bottom, in the order that they appear.


Now, let’s discuss different looping statements in java in detail >
    • 1.1) for,
      • Infinite for loop
      • Enhanced for loop
    • 1.2) while,
      • Infinite while loop
    • 1.3) do-while
      • Infinite do-while loop
Difference between while and do-while loop



1.1) for loop
Loop allows us to use perform certain task repeatedly.

Syntax of for loop>

             for(initialization; termination_booleanVal; increment/Decrement){
                   //Statements..
          }


How for loop works internally >
    • initialization - declare and initialize variables.
Only done once (i.e. at start of for loop.)
  • You may declare variables of only same data types
for (int i = 0, j=0; i < 3; i++){}

We have declare variable of int type in for loop, so we cannot declare variables of any other data type.
  • If you haven’t declare any data type, you may initialize variable of different data types.
int i; long l;
for (i = 0, l=0; i < 3; i++){}

We have declare variable of int and long type before loop, so we can initialize both.
or initialize any number of variables separated by comma (,)
    • termination_booleanVal - for loop is executed only when termination_booleanVal evaluates to true.
evaluation is done every time when for loop is called.
    • increment/Decrement - increment/Decrement is done at end of for loop.
Not done in first execution, but is done in all subsequent executions.


Let’s understand How for loop works  internally by program >

          for (int i = 0; i < 3; i++) {
                 System.out.println("i= " + i);
          }

First loop,
    • initialization - declare and initialize i.  Only done once  (i.e. at start of for loop)
    • termination_booleanVal -  i < 3 (i.e. 0<3) evaluates to true.
Program will enter for loop, print i= 0
second loop,
    • increment/Decrement - i++ is called, i becomes 1
    • termination_booleanVal -  i < 3 (i.e. 1<3) evaluates to true.

Program will enter for loop, print i= 1
Third loop,
    • increment/Decrement - i++ is called, i becomes 2
    • termination_booleanVal -  i < 3 (i.e. 2<3) evaluates to true.

Program will enter for loop, print i= 2
Then (Attempt for fourth loop),
    • increment/Decrement - i++ is called, i becomes 3
    • termination_booleanVal -  i < 3 (i.e. 3<3) evaluates to false.

Program will not enter for loop, and exit for loop.

Note : If termination_booleanVal evaluates to true in first loop/evaluation, then for loop statements will not be executed even once.
Program 1.1.1 to demonstrate for loop
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          for (int i = 0; i < 3; i++) {
                 System.out.println("i= " + i);
          }
   }
}
/* OUTPUT
i= 0
i= 1
i= 2
*/


Infinite for loop
As initialization; termination_booleanVal; increment/Decrement) are optional, we may leave all of them

             // infinite loop
          for ( ; ; ) {
          // Statements..
          }


Enhanced for loop
Enhanced for loop can be used used for iterating over >
  • Array or
  • Collection .
Program 1.1.2 to demonstrate enhanced for loop for iterating over Array elements >
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args){
     int[] ar =  {1,2,3};
     for (int n : ar) {
         System.out.println(n);
     }
   }
}
/* OUTPUT
1
2
3
*/

Program 1.1.3 to demonstrate enhanced for loop for iterating over Collection elements >
import java.util.ArrayList;
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args){
     ArrayList<Integer> l =  new ArrayList<Integer>();
     l.add(1);
     l.add(2);
     l.add(3);
    
     for (int n : l) {
         System.out.println(n);
     }
   }
}
/* OUTPUT
1
2
3
*/



1.2) while loop

Syntax of while loop>

            while(booleanVal){
                   //Statements..
          }

If booleanVal evaluates to true then the statements inside while loop are executed.
while loop will continue to execute until booleanVal evaluates to true.


Note : If booleanVal evaluates to false in first loop/evaluation, then while loop statements will not be executed even once.

Program 1.2 to demonstrate while loop
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 0;
          while(i < 3){
                 System.out.println("i= " + i);
                 i++;
          }
   }
}
/* OUTPUT
i= 0
i= 1
i= 2
*/



Infinite while loop

            while(true){
                   //Statements..
          }





1.3) do-while loop

Syntax of do-while loop>

             do {
          //Statements..
          } while (booleanVal);


First statements inside do block are executed, then booleanVal is evaluated.
do-while loop continue to execute until booleanVal evaluates to true.

Program 1.3 to demonstrate do-while loop
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 0;
          do{
                 System.out.println("i= " + i);
                 i++;
          }while(i < 3);
  
   }
}
/* OUTPUT
i= 0
i= 1
i= 2
*/


Infinite do-while loop
            do{
          // Statements..
          }
          while ( true );



Difference between while and do-while loop

while loop
do-while loop
in while loop statements may not be executed even once.

booleanVal is evaluated at top in while loop.
So, Statements inside while loop are executed when booleanVal is true.

If booleanVal evaluates to false in first loop/evaluation, then while loop statements will not be executed even once.

in do-while loop statements are at least executed once.

First statements inside do block are executed, then booleanVal is evaluated.
Program - When while loop statements are not executed even once.


/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 3;
          while(i < 3){
                 System.out.println("i= " + i);
                 i++;
          }
   }
}
/* OUTPUT
*/
Program - Even with same while condition used in do-while, do-while loop statements are at least executed once (as compared to while loop program).

/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 3;
          do{
                 System.out.println("i= " + i);
                 i++;
          }while(i < 3);
  
   }
}
/* OUTPUT
i= 3
*/





Java allows us to use nested Looping statements
    • nested for,
      • nested Enhanced for loop
    • nested while,
    • nested do-while


RELATED LINKS>

Primitive, Custom/reference Data Types, Integer, Floating-Point, Character and String literal, Escape sequence in java, decimal to hexaDecimal and binary conversion program


Arithmetic, Unary, Equality, Relational, Conditional, Bitwise, Bit Shift, Assignment, instanceof operators in detail with programs.


eEdit
Must read for you :