condition : Check the logic and it should return true or false.
The code block is executed only if the condition is true
Example 1
int i=0;
while( i < 5) {
System.out.println(i);
i=i+1;
}
Output
0
1
2
3
4
In above code we are first printing the value of the variable and then incrementing the value of variable by 1. So the output prints 0 to 4 and not 0 to 5.
Understanding condition
In place of using integer variable and incrementing , we will use one Boolean variable with initial value set to true. Inside the loop we will set the value of the variable to false. As expected the loop will execute once only.
What happens if the condition never became false. We will create one infinite loop.
int i=0;
while( i < 5) {
System.out.println(i);
i=i-1;
}
What will happen if the condition is false always ?
The code block will never execute.
This is the main difference between while loop and do while loop.
while loop with break and continue
Inside the loop of we use break; satement then the execution will come out of the loop.
Example using break
int i=0;
while( i < 5) {
i=i+1;
if(i==2) {
break;
}
System.out.println(i);
}
Output is here
1
After printing 1 ( first iteration ), i value will be equal to 2, so the break statement will be encountered and the execution will come out of the loop.
Example using continue
In above code we will replace break with continue.
Except printing 2 , all values from 1 to 5 will be printed. When i value became 2, the continue statement is encountered and execution returns to be starting of the loop without executing print command.
Difference between break and continue
The execution stops and comes out of the loop once break statement is encountered. In case of continue, further execution of the code block is stopped and loop continues from starting of the loop.