Java while-do and do-while loop syntax

Contributor Icon Contributed by Rex Date Icon September 9, 2004  
Tag Icon Tagged: Java programming

The while loop in Java allows a loop block to be executed an arbitrary number of times until a condition is met. This recipe shows the basic syntax of the Java while loop.


The while loop in Java can be used in two ways, while-do and do-while. The while-do form allows the condition to be tested before the code block is executed, so it is possible for the code block never to be executed. The do-while syntax, like the repeat-until syntax of other languages, does not check the condition until after the loop code block is executed, so the code block will always be run at least once with do-while.

The generic while-do syntax is:

while (condition)
{
code_block;
}

While we refer to this flavor of while loop as “while-do” it is important to note that the keyword “do” is not used. The do-while syntax does use the “do” keyword:

do {
code_block;
} while (condition);

The condition can be any valid Java expression that evaluates to a boolean value. The code block can be any valid Java code. If only one line of Java code is required in the code block, the curly braces are optional, but many programmers leave them in to make their code more readable.

Previous recipe | Next recipe |
 

Viewing 1 Comment

    • ^
    • v
    I need a java program that will repeatedly read temperatures in Fahrenheit and convert them to Celsius until a temperature > 212 F is entered. I really need this, please, and thank you. mbnumba14@yahoo.com(email address)

    Here is my java program:
    import java.util.*;
    // Converter.java
    public class Converter
    {
    public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter temp: ");
    int temp = sc.nextInt();
    System.out.println(convertToC(temp));
    }
    public static int convertToC(int temp)
    {
    return ((temp - 32 ) * 5/9);
    }
    }
    .
 
close Reblog this comment
blog comments powered by Disqus