Home » Online Computer Education » Learn Fundamentals of Java Programming “The while statement in Java Programming ” Lesson 12

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.

Java fundamentals  flow control 5

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

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