Loop statement

Java has very flexible three looping mechanisms. You can use one of the following three loops:

  • while Loop
  • do...while Loop
  • for Loop

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

while(Boolean_expression)
{
   //Statements
}

The do...while Loop:

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

do
{
   //Statements
}while(Boolean_expression);

The for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.
Syntax:

for(initialization; Boolean_expression; update)
{
   //Statements
}

Example:

PROGRAM-1: WRITE A PROGRAM IN JAVA TO PRINT MESSAGE "HELLO JAVA " 10 TIMES ON THE SCREEN?
Note: create a java file "softaid.java" and write the following contents.

/*    WRITE A PROGRAM IN JAVA TO PRINT MESSAGE 
HELLO JAVA  10 TIMES ON THE SCREEN	*/
public class softaid 
{
	public static void main(String[] args) 
	{
		String message="Hello java ..";
		int i;
		
		//USING FOR LOOP
		for(i=0;i<10;i++) 
		{
		System.out.print(" "+message);
		}	
		
		System.out.println(" ");
		//USING WHILE LOOP
		i=0;
		while(i<10)
		{
			System.out.print(" "+message);
			i++;
		}		
		System.out.println(" ");
		//USING DO-WHILE LOOP 
		i=0;
		
		do
		{
			System.out.print(" "+message);
			i++;
		}while(i<10);
		
	}
}

PROGRAM-2: WRITE A PROGRAM TO PRINT SQUARE AND QUBE VALUE FROM 1 TO 20.

/*    WRITE A PROGRAM TO PRINT SQUARE AND
 QUBE VALUE FROM 1 TO 20 */
public class softaid 
{
public static void main(String[] args) 
{
int n=1;
//USING FOR LOOP 
for(n=1;n<=20;n++)
{
System.out.println
("Number : "+n+" Square : "+(n*n)+" , QUBE : "+(n*n*n));
}
//USING WHILE LOOP
System.out.println(" ");
n=1;
while(n<=20)
{
System.out.println
("Number : "+n+" Square : "+(n*n)+" , QUBE : "+(n*n*n));
n++;
}
// USING DO-WHILE LOOP
System.out.println(" ");
n=1;
do
{
System.out.println
("Number : "+n+" Square : "+(n*n)+" , QUBE : "+(n*n*n));
n++;
}
while(n<=20);
}
}