Programming languages provide various control structures that allow for more complex execution paths.
A loop statement is used to execute a statement or a group of statements multiple times, following is the general form of a loop statement in most programming languages −
The Java programming language provides the following types of loops to handle looping requirements, which can be learned by clicking on each of the links below.
serial number | cycle | describe |
---|---|---|
1 | while loop | Repeats a statement or group of statements while a given condition is true, it tests the condition before executing the loop body. |
2 | for loop | Executes a series of statements multiple times and abbreviates the code that manages loop variables. |
3 | do...while loop | Like while statement, but it tests the condition of the loop body at the end. |
Loop control statements alter execution from the normal execution order. When execution leaves a scope, all automatic objects created in that scope are destroyed.
Java supports the following control statements which can be understood and learned by clicking on each link below.
serial number | control statement | describe |
---|---|---|
1 | break statement | Terminates a loop or switch statement and immediately transfers execution to switch the statement on or after the loop. |
2 | continue statement | Causes the loop to skip the rest of its body and immediately retests its state before repeating. |
Starting with Java 5, enhanced for
loops were introduced. This is primarily useful for traversing collections of elements, including arrays.
Syntax
Following is the syntax of boost for
loop −
for(declaration : expression) {
// Statements
}
In the syntax above,
declaration
- The newly declared block variable is of a type compatible with the array element to be accessed. The variable will be available in the for block and its value will be the same as the current array element.expression
- This is the array to loop through. expression( expression
) can be a returned array variable or a method call.example
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Curry", "Kobe", "Jordan"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
Executing the above sample code yields the following result −
10, 20, 30, 40, 50,
James, Curry, Kobe, Jordan,
The while loop in Java works similar to that in Python. It allows us to execute a block of code several times as long as the condition evaluates to true.
There is only a syntactical difference when compared to Python. In Python, the block of code is separated by indentation, whereas in Java the curly braces {} are used.
while (condition) { // body of loop } |
The following code snippet prints the next three consecutive numbers after a given number.
class Main { public static void main(String[] args) { int num = 4; int counter = 0;
while (counter < 3) { num = num + 1; System.out.println(num); counter = counter + 1; } } } |
5
6
7
Let's take a look at some of the most common mistakes that happen when using loops.
1.1.1 Incorrect Termination Condition
class Main { public static void main(String[] args) { int num = 4; int counter = 0; boolean condition = (counter < 3);
while (condition) { num = num + 1; System.out.println(num); counter = counter + 1; } } } |
Time Limit Exceeded
The above code runs into an infinite loop. The while block will keep executing as the value in the condition variable is always true
1.1.2 Not Updating Counter Variable
class Main { public static void main(String[] args) { int n = 4; int counter = 0;
while (counter < 3) { n = n + 1; System.out.println(n); } } } |
Time Limit Exceeded
In the above code, we are not updating the counter variable inside the while loop. Since the counter value does not change, the condition will always evaluate to be true, resulting in an infinite loop.
The do...while loop is similar to the while loop. The only difference is that in the while loop the condition check is made initially, whereas in the do...while loop the check is made after the do...while block of code has been executed.
Syntax
do { // body of loop } while(condition); |
Now, let's write the code to print the next three numbers from a given number using do...while loop.
class Main { public static void main(String[] args) { int n = 4; int counter = 0;
do { n = n + 1; System.out.println(n); counter = counter + 1; } while (counter < 3); } } |
5
6
7
The do-while loop is executed at least once regardless of the condition.
The following code snippet prints the output for once even though the condition is false
class Main { public static void main(String[] args) { int n = 3; boolean condition = (n > 10);
do { System.out.println("Number is greater than 10"); } while (condition); } } |
Number is greater than 10
Note: Python does not have an equivalent syntax for do-while loop
Java for loop is used to execute a block of code a certain number of times. It is generally used where the number of iterations is known.
Syntax
for (initialExpression; condition; increment/decrement) { // body of the loop } |
initialExpression: Here, the variables are defined or initialized. initialExpression is executed only once.
condition: It is evaluated for every iteration of the loop. If the condition evaluates to true, the body of the for loop is executed.
increment/decrement: Here, the initialExpression is updated. It is executed at the end of every iteration of the for loop.
The condition is evaluated again. This process continues until the condition evaluates to false
The below for loop iterates three times and prints the next three numbers after the given number.
class Main { public static void main(String[] args) { int num = 4;
for (int counter = 0; counter < 3; counter = counter + 1 ) { num = num + 1; System.out.println(num); } } } |
5
6
7
Wrong Loop Syntax
Leaving out the semi-colons in a for loop or replacing them with any other special characters such as commas (,) will result in an error.
class Main { public static void main(String[] args) { int num = 4;
for (int counter = 0, counter < 3; counter = counter + 1 ) { num = num + 1; System.out.println(num); } } } |
file.java:5: error: ';' expected for (int counter = 0, counter < 3 ; counter = counter + 1 ) { ^ file.java:5: error: illegal start of type for (int counter = 0, counter < 3 ; counter = counter + 1 ) { ^ file.java:5: error: ')' expected for (int counter = 0, counter < 3 ; counter = counter + 1 ) { ^ file.java:5: error: ';' expected |
Enhanced loops are used to traverse collection of elements like Collection classes like List, Map, and Arrays also
Syntax
for(declaration : expression) { // Statements } |
Declaration − The newly declared block variable, is of a type compatible with the elements of the array we are accessing. The variable will be available within the for block and its value would be the same as the current collection/array element.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array
Example code for Enhanced loop
public class LoopTest { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] loops = {"Loop", "While Loop", "Do While Loop", "For Loop"}; for( String loop : loops ) { System.out.print( loop ); System.out.print(","); } } } |
Conclusion
In for and while loops, the condition is checked before the execution of the corresponding block of code.
In do...while loop, the condition is checked after the execution of the corresponding block of code. The do...while loop is executed at least once