Java while and the do while loop statements

The while and the do while statements in Java Programming.

We will introduce you to other types of looping statement in Java (while and do while loop).

while loop

while loop is a control structure in Java that executes a block of statements while a condition is true.

Here’s the structure or general format of writing a while loop:

while(condition)
{
loopBody        // yourJavaStatements
}

Where:

condition or the boolean expression is an expression to be tested if true, once the condition is still true the loop will continue,
the loop will end when the condition is no longer true.

loopBody this is where you put your Java statements that you want to execute. Your Java statements will run as long the condition is true. Your loopBody can be a simple or compound statement. It is also where you put statement in which you’re going to update the value of your variable.

Java while loop
Java while loop

Example:

import java.util.*;

class whileLoop{

static Scanner console = new Scanner(System.in);

public static void main(String[] args){

int num;

System.out.print("Enter a number from 1 to 20:");

num = console.nextInt();

while( num < 20 ) {

System.out.print("value of num : " + num );

num++;

System.out.print("\n");

}

}
}

Explanation:

  1. The program will ask you to enter a number from 1 to 20.
  2. The while statement will then evaluate if the number that you have entered is less than 20, if true, then the program will print the current value of the number.
  3. The number that you have entered will then increment by 1.
  4. The while statement will then re-evaluate the condition, still if true, it will continue to execute the block of codes.
  5. The while loop will end if the condition is no longer true.

The do while loop statement

In the while loop the condition if found on the top of the statement, whereas in the do while loop the condition is at the bottom, which means that the block of codes in the do block will always be executed once.

The structure of the do while loop:

do
{
loopBody        // yourJavaStatements
}while(condition);

Example:

import java.util.*;

class doWhileLoop{

static Scanner console = new Scanner(System.in);

public static void main(String[] args){

int num;

System.out.print("Enter a number from 1 to 10:");

num = console.nextInt();

do{

System.out.print("value of num : " + num );

num++;

System.out.print("\n");

}while( num < 20 );

}
}

Note: since the condition is located at the bottom of the code, the case here is that, if the user enters 20, the program will still execute the block of codes and display the value before evaluating condition.

,

Post navigation

One thought on “Java while and the do while loop statements

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.