JAVA do while loop: introduction

java do while loop tutorial for beginners

The JAVA do while loop statement is used to repeat a set of instructions multiple times.

In the JAVA do while loop, the number of repetitions is not known in advance.

JAVA do while loop: syntax

do {

<statement_or_block>

} while ( <test_expr> );

You should not forget the semicolon “;” after the while keyword.

The body of the JAVA do while loop is executed at least once.

There is no prior condition to verify before the execution of the body of the do while loop.

In fact, the body of the JAVA do while loop is repeated until the test_expr condition becomes false.

If the test_expr condition never becomes false, we fall in an infinite loop and our program will fail.

JAVA do while loop  Examples:

public class TestDoWhile {
public static void main(String[] args) {
int i = 0;
do {
System.out.println("This is the line number " + i);
i++;
} while (i < 4);
}
}

This code displays the message: “This is the line number i” 4 times in the console.

The i variable is incremented in each iteration (the i++ instruction does the incrementation).

The result of the execution of this program is the following:

This is the line number 0

This is the line number 1

This is the line number 2

This is the line number 3

Special Loop Flow Control

Java while loop and the break keyword

The break keyword finishes the loop statement.

It is generally used to stop the execution of the do while loop if some condition is true.

public class
TestDoWhile {
public static void main(String[] args) {
int i = 0;
do {
if (i == 2) {
break;
}
System.out.println("This is a new line number " + i);
i++;
} while (i < 4);
}
}

The output of this code is the following:

This is the line number 0

This is the line number 1

Java while loop and the continue keyword

The JAVA continue keyword is used to skip one iteration.

public class TestDoWhile {
public static void main(String[] args) {
int i = 0;
do {
if(i == 2) {
i++;
continue;
}
System.out.println("This is a new line number " + i);
i++;
} while (i < 4);
}
}

The output of this code is the following:

This is the line number 0

This is the line number 1

This is the line number 3

We notice that we skipped the processing of the line number 2.

In fact, we skipped the display of the message for the line number 2.

This core JAVA tutorial which deals with java while loop statement arrives at its end.

To check the other JAVA loop statements, please check this tutorial.

Please, don’t forget to follow us on Facebook to get our next JAVA core tutorial.

Post a Comment

Previous Post Next Post