while ( condition ){
// code block to execute
}
condition : Check the logic and it should return true or false.
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.
boolean my_condition=true;
while( my_condition ) {
System.out.println(my_condition);
my_condition=false;
}
Output is
true
int i=0;
while( i < 5) {
System.out.println(i);
i=i-1;
}

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.
while( i < 5) {
i=i+1;
if(i==2) {
continue;
}
System.out.println(i);
}
Output is here
1
3
4
5
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.