How do you execute a 'while' loop in Java?
What is a loop?
When programming, you will encounter blocks of code that are to be repeated over and over again until a specific requirement becomes false. Hence, this block of code will run in a loop.
One specific type of loop is a while loop. This form of a loop continues to run as long as a specific condition returns true. A while loop follows the syntax given below:
class HelloWorld {public static void main( String args[] ) {while(condition){//body of loop}}}
Syntax
Look at the code above from lines 4 to 6 to understand the syntax of a while loop in Java:
- A
whilekeyword is followed by round brackets,() - Within these brackets, the
conditionis written - This
conditionis checked each time a loop is run. If the condition returnstruethen the loop body executes, otherwise the loop breaks.
The illustration below shows the logical route that a while loop follows:
Example
Now that we know what syntax the while loop follows and how to write it, let’s look at a few coding examples.
1. Starting while with a false condition
The example below shows what happens when you execute a while loop when the condition is false such that the loop does not execute even once:
class HelloWorld {public static void main( String args[] ) {int i=10;while(i<5){System.out.println("The value of i: "+ i);}}}
2. Executing a while loop
The example below shows how the loop runs until the conditional statement returns false. For each iteration of the loop, the value of i is doubled. When the value becomes greater than 30, the loop should terminate.
class HelloWorld {public static void main( String args[] ) {int i=1;while(i<30){System.out.println("The value of i is "+ i);i=i*2;}}}
3. Using while to iterate over an array
We can even use while loops to iterate over an array.
-
First we define an
arrayand find out its length,len, using thelengthproperty of arrays. -
Then we define an
indexvariable to iterate over thearray. -
The while loop, from lines 6 to 9, is run till
indexbecomes equal tolenindicating that the entire array is traversed. -
In each iteration, the loop condition checks if the
indexis less thanlen. If the result of the expression is true, i.e.indexis less thanlen, then the value of the array atindexis printed andindexis incremented
The example below shows how it can be done:
class HelloWorld {public static void main( String args[] ) {int array [] = {5,4,3,2,1};int len = array.length;int index = 0;while(index<len){System.out.println(array[index]);index = index + 1;}}}
Free Resources