What is the difference between a for loop and a while loop in java?

Answer:

Comparison

The conditions for both the 'while' and 'for' loop are exactly the same, but in each flow structure the conditions are placed in different locations. A 'for' loop places the full condition within the 'for' loop whereas the 'while' loop places the counter variable outside of the loop.

The 'for' loop is used when the length of the loop is known whereas the 'while' loop is usually used when the length of the loop is unknown.

'for' loop example

Within the parentheses the complete condition is contained. The condition has 3 parts delimited by a colon ';'. The first part sets the counter 'int i' to 0, the second part tells the loop to stop when the counter is 5. The third part tells java to increment the counter by 1 value each time the loop iterates.

for ( int i = 0; i < 5; i++)


'while' loop example

With the 'while' loop the counter is initialized outside of the 'while' loop. Inside the parentheses of the loop the condition is set to stop looping when the counter reaches a value of 5. Inside of the 'while' loop block the counter is set to increment by 1 value each time the loop iterates.

int i = 0;

while ( i < 5 ) {
i++
}
First answer by R1B Coder. Last edit by R1B Coder. Contributor trust: 20 [recommend contributor recommended]. Question popularity: 1 [recommend question].