Java Loops

Loops are used to repeat the execution of a statement or block of statements while the provided condition returns true. There are following type of java loops.

Java For Loop

for loop executes a bunch of statements continuously to accomplish a particular condition. A for loop is used when you know how many time a block of code to be repeated.

For Loop Syntax

for(initialization; condition; update)

{

//for loop body

}

Initialization: initialize the loop control variable

Condition: a boolean expression

Update: update loop control variable

For Loop Example

public class JavaLoop {

public static void main(String args[]) {

for(int i = 1; x <= 10; i++) {

System.out.print(“i = ” + i );

System.out.print(“\n”);

}

}

}

Output:

i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10

Java While Loop

The while loop is used when you don’t want to repeat the execution of the code for a specific number of time. Instead you want to repeatedly execute code until a specified condition is met. The condition is tested each time before execution of the loop body.

While loop syntax

while(condition)

{

//while loop body

}

While loop example

public class JavaLoop{

public static void main(String args[]) {

int i = 1;

while( i <= 10 ) {

System.out.print(“Repetition number = ” + i );

System.out.print(“\n”);

i++;

}

}

}

Output:

Repetition number = 1
Repetition number = 2
Repetition number = 3
Repetition number = 4
Repetition number = 5
Repetition number = 6
Repetition number = 7
Repetition number = 8
Repetition number = 9
Repetition number = 10

Java do..while loop

The only difference between while and do..while loop is that the body of do..while is executed before testing the condition which mean the body of do..while loop will be executed at least once.

do..while loop syntax

do

{

//do..while loop body

} while(condition);

do..while loop example

public class JavaLoop{

public static void main(String args[]) {

int i = 1;

do {

System.out.print(“Repetition number = ” + i );

System.out.print(“\n”);

i++;

} while( i <= 10 );

}

}

Output:

Repetition number = 1
Repetition number = 2
Repetition number = 3
Repetition number = 4
Repetition number = 5
Repetition number = 6
Repetition number = 7
Repetition number = 8
Repetition number = 9
Repetition number = 10

Leave a Reply

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