While Loop in Java is a control flow statement which executes repeatedly a block of code as long as the boolean condition in the while loop remains true . The while loop is mostly used when the number of iteration is not known before and the loop needs to be continue until the specific condition is true.
Syntax of Java While Loop:
while ( condition ) {
//code to be executed repeatedly as long as the condition is true
}
while keyword : This while keyword initiates the while loop.
condition: This is a boolean expression which is evaluated before each iteration of while loop.
* If the condition evaluates to be true , the code inside the while loop will execute
* If the condition evaluates to be false , the while loop terminates and the program continues with the
statement immediately after the following while loop .
Example 1:
int count= 0;
while ( count < 7 ) {
System.out.println(“Count is : “+ count);
count++;
}
System.out.println(“while loop is finished”);
Example 2 : print the numbers from 1 to 7 using while loop
int i=1;
while ( i < 8 ) {
System.out.println(i);
i++ ;
}
Example 3 : Print the “Happy Birthday” after count down from 3 to 1 using while loop
int countdown = 3;
while ( countdown >0 ) {
System.out.println(countdown);
countdown–;
}
System.out.println(” Happy Birthday “);
while Loop with False Condition :
If the condition inside the while loop is false at the beginning , the code inside the while loop will never run.
Example:
int i= 15;
while ( i < 10 ) {
System.out.println(“This will never print as the condition inside the while loop is false at the beginning”);
}
