DIFFERENCE BETWEEN 'FOR LOOP' AND 'WHILE LOOP' IN JAVA:

S.NO

                         FOR LOOP

        WHILE LOOP

1)Initialization may be either in loop statement or outside the loop.Initialization is always outside the loop.
2)Once the statement(s) is executed then after increment is done.Increment can be done before or after the execution of the statement(s).
3)It is normally used when the number of iterations is known.It is normally used when the number of iterations is unknown.
4)Condition is a relational expression.Condition may be expression or non-zero value.
5)It is used when initialization and increment is simple.It is used for complex initialization.
6)For is entry controlled loop.While is also entry controlled loop.
7)

for ( initial ; condition ; iteration )
{

 statement(s); 

}

while ( condition )

statement(s); 

}

EXAMPLE PROGRAMS:

FOR LOOP:

// Java program to find sum of given ranges using for loop

public class summation { 
	public static void main(String args[]) 
	{ 
		int sum = 0; 

		// for loop begins 
		// and runs till x <= 20 
		for (int x = 1; x <= 20; x++) { 
			sum = sum + x; 
		} 
		System.out.println("Sum: " + sum); 
	} 
} 

OUTPUT:

             Sum: 210

WHILE LOOP:

// Java program to find sum of given ranges using while loop

public class summation { 
	public static void main(String args[]) 
	{ 
		int x = 1, sum = 0; 

		// Exit when x becomes greater than 4 
		while (x <= 20) { 
			// summing up x 
			sum = sum + x; 

			// Increment the value of x for 
			// next iteration 
			x++; 
		} 
		System.out.println("Sum: " + sum); 
	} 
} 

OUTPUT:

             Sum: 210

PROGRAM EXPLANATION:

  • The example program for 'for loop' and 'while loop' are the same, and having same output.  But the working principle of for loop and while loop is slightly different.

 

  • for 'for loop': First take the initialization and check the condition.  If the condition is true, then the block of statements inside for loop(i.e) summation will be executed.  Else the statements outside the body of for loop will be executed.

 

  • for 'while loop': Here initialization will takes place in outside the while loop, then Check the condition.  If the condition is true, then the block of statements inside while loop (i.e) Summation will be executed.  Else the statements outside the body of while loop wil be executed.

 

      “Education without application is just entertainment.”
                                                                                    — Tim Sanders