There can be a situation where you need to execute a block of code again and again for a specific number of times. For example, imagine you have to write a program that performs a repetitive task such as printing 1 to 1000. Coding 1000 lines to do this would be mundane and stupidity. Computers are now very smart and meant to reduce the task, although the computer would not mind executing your 1000 lines but still it wants you to play smart on that. This is where loops come into the picture. Loops are specifically designed to perform repetitive tasks with one set of code. Loops save a lot of time.
Loops in Java:
As explained above - Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
In Java we have three types of basic loops: for, while, and do-while.
What are the various types of Loops in Java?
-
The for loop : This executes a statement for a particular number of times
-
The while loop : This executes a statement for an unknown number of times
-
The do-while loop : This executes a statement at least for one time
-
Enhanced for loop : This for loop also works with an array of any types
The for Loop in Java
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. The syntax for "for" loop is :
for(Variable Initialization; Boolean_Expression Test; Increment/Decrement){
//Statements
}
Let's try to understand the above code. It is divided into four parts:
- Variable Declaration : This part is the very first part and called as Variable Initialization. This specifies that at what number you want to start looping and this being executed only once in the complete loop process.
- Condition : The second part uses some conditional logic in which regular expression is evaluated. The body of the loop is executed only if the condition is true. In case of false, the flow of the loop jumps out of the loop.
- Body : As said above, this executes only if the condition of the expression is true. Body can be the series of steps and can have another for loops as well. The body very often makes use of variable declared in the first part of the loop.
- Increment Statement : Once the body is executed, the flow goes to this statement and change the value of the variable declared in the first part of the loop. Actually it increments the value in case of ++ and decrements the value in case of --.
Example
package javaTutorials;
public class For_Loop {
public static void main(String[] args) {
// This will print -- 0,1,2,3,4,5
for(int Increment = 0;Increment<=5;Increment++){
System.out.println("Count is ==> " + Increment );
}
System.out.println("<==== Next Count ====>");
// This will print -- 5,4,3,2,1,0
for(int Decrement = 5;Decrement>=0;Decrement--){
System.out.println("Count is ==> " + Decrement );
}
System.out.println("<==== Next Count ====>");
// This will print -- 0,2,4
for(int Increment = 0;Increment<=5;Increment+=2){
System.out.println("Skip every one another ==> " + Increment );
}
}
}
Output
Count is ==> 0
Count is ==> 1
Count is ==> 2
Count is ==> 3
Count is ==> 4
Count is ==> 5
<==== Next Count ====>
Count is ==> 5
Count is ==> 4
Count is ==> 3
Count is ==> 2
Count is ==> 1
Count is ==> 0
<==== Next Count ====>
Skip every one another ==> 0
Skip every one another ==> 2
Skip every one another ==> 4
Lets now try to understand the usage of a couple of keywords break and continue
- The break keyword - There are two ways to coming out of the loop, first is when the boolean expression becomes false and second is the break keyword which helps to come out of the loop before completing the full cycle of the loop. For example, there can be situations when you like to jump out of the loop when you met with some specific conditions. This is achieved with the keyword break. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the for loop block.
Example
package javaTutorials;
public class Break_Loop {
public static void main(String[] args) {
// This will print -- 0,1,2,3,4,5
for(int Count = 0;Count<=10;Count++){
if(Count==6){
break;
}
System.out.println("Count is ==> " + Count );
}
System.out.println("You have exited the loop");
}
}
Output
Count is ==> 0
Count is ==> 1
Count is ==> 2
Count is ==> 3
Count is ==> 4
Count is ==> 5
You have exited the loop
- The continue keyword - The continue keyword helps to avoid the execution of the body of the loop in some specific situation. Like break, when you like to jump out of the loop, there may be some situation when you just want to skip some condition. The continue keyword causes the loop to immediately jump to the next iteration of the loop and it can be used in any of the loop control structures.
Example
package javaTutorials;
public class Continue_Loop {
public static void main(String[] args) {
// This will print -- 0,1,2,4,5
for(int Count = 0;Count<=5;Count++){
if(Count==3){
continue;
}
System.out.println("Count is ==> " + Count);
}
// This will just print -- 3
System.out.println("<==== Next Count ====>");
for(int Count = 0;Count<=5;Count++){
if(Count==3){
System.out.println("Count is ==> " + Count);
continue;
}
}
}
}
Output
Count is ==> 0
Count is ==> 1
Count is ==> 2
Count is ==> 4
Count is ==> 5
<==== Next Count ====>
Count is ==> 3
The while Loop in Java
While loop is also a control structure like for loop which allows you to repeat a task for a number of times. The only difference between a while loop and for loop is that the for loop repeats the task for a specific number of times but the while loop repeats the task for an unknown number of times. The syntax for the while loop is :
while(Boolean_Expression Test){
//Statements
}
Let's try to understand the above code. It is divided into two parts:
- Condition : Unlike for loop this loop does not have any initialization part. This part uses some conditional logic in which regular expression is evaluated and the body of the loop is executed till the time condition is true. In case of false, the flow of the loop jumps out of the loop.
- Body : As said above, this executes till the time condition of the expression is true. But a body may not execute even once if the condition returns false at the very start of the while loop.
Example
package javaTutorials;
public class While_Loop {
public static void main(String[] args) {
int Count = 0;
// This will print -- 5,10,15,20,25
while(Count < 25){
Count = Count + 5;
System.out.println("Count is ==> "+ Count);
}
int CountOnce = 25;
System.out.println("<==== Next Count ====>");
// This will not print count even once
while(CountOnce < 25){
CountOnce = CountOnce + 5;
System.out.println("Count is ==> "+ CountOnce);
}
}
}
Output
Count is ==> 5
Count is ==> 10
Count is ==> 15
Count is ==> 20
Count is ==> 25
<==== Next Count ====>
The do-while Loop in Java
A do-while loop is exactly similar to while loop and the only difference between two is that the do-while loop executes the statement at least one time. As it starts with do keyword and the boolean expression appears at the end of the loop. the syntax for do-while loop is :
do{
//Statements
}while(Boolean_Expression Test);
Example
package javaTutorials;
public class DoWhile_Loop {
public static void main(String[] args) {
int Count = 0;
// This will print -- 5,10,15,20,25
do{
Count = Count + 5;
System.out.println("Count is ==> "+ Count);
}while(Count < 25);
int CountOnce = 25;
System.out.println("<==== Next Count ====>");
// This will just print once
do{
CountOnce = CountOnce + 5;
System.out.println("Count is ==> "+ CountOnce);
}while(CountOnce < 25);
}
}
Output
Count is ==> 5
Count is ==> 10
Count is ==> 15
Count is ==> 20
Count is ==> 25
<==== Next Count ====>
Count is ==> 30
Enhanced for loop in Java
The enhanced for loop allows you to iterate through a collection without having to create an Iterator or without having to calculate beginning and end conditions for a counter variable. This enables you to use loops over array objects of any type.
In selenium WebDriver it is very helpful when you need to iterate through the array of WebElements. Syntax for enhanced for loop is :
for (data_type variable: array_name)
Example
package javaTutorials;
public class Enhanced_Loop {
public static void main(String[] args) {
// Array of String storing days of the week
String days[] = { "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun"};
// Enhanced for loop, this will automatically iterate on the array list
for (String dayName : days) {
System.out.println("Days ==> "+ dayName);
}
System.out.println("<==== Normal For Loop ====>");
// Normal for loop
for (int i=0; i < days.length; i++) {
System.out.println("Days ==> "+ days[i]);
}
}
}
Output
Days ==> Mon
Days ==> Tue
Days ==> Wed
Days ==> Thr
Days ==> Fri
Days ==> Sat
Days ==> Sun
<==== Normal For Loop ====>
Days ==> Mon
Days ==> Tue
Days ==> Wed
Days ==> Thr
Days ==> Fri
Days ==> Sat
Days ==> Sun