This tutorial will take you step by step through the process of understanding and using the while statement. The best way to learn is to compile and run these programs yourself (copy, paste, compile and run !). Comments such as /* this is a comment */ or // this is another comment are inserted to explain what does the line of code do. The programs are kept simple for the purpose of concentrating on the main idea in question.
Example 1: while statement
class While1{
public static void main(String args[]){
int x = 0;
while(x<10){
System.out.println("x = "+x);
++x;
}
System.out.println("execution continues here ...");
}
}
Examine the output, note that the statement "System.out.println("x = "+x)
executes as long as x<10. As soon as x>=10 execution branches out of
the body of the while statement and continues. Try to start with an initial
value of x >= 10, execution of the while statement will not start at ALL.
Example 2: do-while statement
The main difference between the do-while and the while is that the body of the do-while statement gets executed at least once.
class While2{
public static void main(String args[]){
int x = 20;
do{
System.out.println("x = "+x);
++x;
}while(x<10);
System.out.println("execution continues here ...");
}
}
The body of the do-while executes once (even if x does not satisfy the
condition x < 10).
Return to : Java Programming Hints
and Tips