Loops are an essential part of any programming language, including Java. In this blog post, we will discuss three types of loops available in Java, namely while
, do-while
, and for
loops, along with example code and commands.
- While Loop The
while
loop is used to repeat a block of code as long as a specified condition is true. Here’s an example of how to use awhile
loop in Java:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
This code will print out the numbers 0 to 4, because the loop will continue running as long as the value of i
is less than 5.
- Do-While Loop The
do-while
loop is similar to thewhile
loop, except that it will always run the code block at least once, regardless of whether the condition is initially true or not. Here’s an example:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
This code will also print out the numbers 0 to 4, but the difference is that the loop will always run the first time, even though the value of i
is initially 0.
- For Loop The
for
loop is used to repeat a block of code a specified number of times. It is commonly used when you know the exact number of times you want to run the loop. Here’s an example of afor
loop:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
This code will also print out the numbers 0 to 4, but the for
loop has a different syntax than the while
and do-while
loops. The loop variable is declared and initialized in the first part of the loop declaration, the condition is checked in the second part, and the loop variable is updated in the third part.
- For-Each Loop The
for-each
loop is used to iterate over the elements of an array or a collection in a simple and concise way. It is also known as the “enhanced for loop.” Here’s an example:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
This code will print out the numbers 1 to 5 because the for-each
loop automatically iterates over the elements of the numbers
array.
In addition to the basic while
, do-while
, and for
loops, Java also provides additional features for controlling loops. For example, the break
statement can be used to exit a loop prematurely, and the continue
statement can be used to skip to the next iteration of the loop.
Here’s an example of using break
in a while
loop:
int i = 0;
while (true) {
if (i == 5) {
break;
}
System.out.println(i);
i++;
}
This code will print out the numbers 0 to 4 and then exit the loop, because the break
statement is executed when i
reaches 5.
Overall, loops are an essential tool for any Java programmer and the while
, do-while
, and for
loops provide different ways of controlling program flow based on specific conditions. By understanding how to use these loops, you can create more sophisticated and efficient Java programs.