While Statement Introduction in Java

Posted By: Java Examples - 9:59 AM

Share

& Comment

The while statement is used to repeat a block of statements while some condition is true. The condition must become false somewhere in the loop, otherwise it will never terminate. 

Purpose :
Purpose - to repeat statements The purpose of the while statement is to repeat a group of Java statements many times. It's written just like anif statement, except that it uses the while keyword. 


General Form :
The while statement has this form :

while (condition) {
     ...statements to repeat while the condition is true
   }

Condition is true or false The value of condition must be true or false (ie, a boolean value). It is often a comparison (see example below).

Example : 
Loop continues while the condition is true ,print square numbers between 1 to 10
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package statement;

/**
 *
 * @author ACHCHUTHAN
 */
public class WhileExample {

    public static void main(String args[]) {
        int n = 1;
        while (n <= 10) {
            System.out.println("square of " + n + "\t : " + (n * n));
            n++;
        }
    }
}

Output of this program :

run:
square of 1 : 1
square of 2 : 4
square of 3 : 9
square of 4 : 16
square of 5 : 25
square of 6 : 36
square of 7 : 49
square of 8 : 64
square of 9 : 81
square of 10 : 100
BUILD SUCCESSFUL (total time: 1 second)

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .