Learn Fundamentals of Java Programming “The while statement in Java Programming ” Lesson 12
The while statement
The while statement evaluates the test before executing the body of a loop. The structure of the Java while statement is as below:
while (expression)
{
statements
}
Let us write a program to print the squares of numbers from 1 to 5. The following steps need to be performed.
1. Initialize number = 1
2. Test if the number <= 5
3. If yes, print the square of the number;
Increment number (number = number + 1)
Go back to step 2
If no, exit the loop.
The tasks that need to be performed repeatedly are in step 3 – these constitute the body of the loop. The test condition is in step 2. The corresponding Java code is given below:
public class WhileDemo {
public static void main(String[] args) {
int number = 1;
while (number <= 5) {
System.out.print (“Square of ” + number );
System.out.println( ” = + number *number);
++number ;
}
}
}
Note the use of the ++ operator to increment the value of number. The statement ++number or number++; is the same as number = number + 1;
The output from the WhileDemo program is displayed in Figure 1.4f.