Loop Statements in Java

Understanding Loops in Java

Understanding Loops in Java

In the second part of this Java tutorial on control statements, this blog post we will help you in understanding loops in Java. The loop constructs like while…. and For… are used in java to write logic for multiple iterations.

Read Also: Control Statements in Java

 

What are loop statements in Java?

There are 3 different types of loops in Java. They are FOR LOOP, WHILE LOOP and DO WHILE LOOP. Apart from these 3 main types we do have FOR EACH LOOP which differs in syntax when compared with FOR LOOP.

However the only difference is that FOR EACH LOOP is an “enhanced FOR LOOP”, introduced in Java 5. Also when handling collections of objects FOR EACH is significantly faster then FOR LOOP.

For…. Loop

For…..loops are used if you want to iterate a part of program for certain number of times. If you are aware of the number of iterations, it is always advisable to use java for loop:

Let’s look at the syntax of for loop:

for (initialization; condition; increment / decrement)

{

//’n’ Statements to be executed

}

Let’s understand the arguments in the for…loop:

initialisation Here you need to initialise the variable i.e. the starting value from where your for…loop will begin to execute

eg: k = 0; => Here variable k is been initialised to 0 and the loop will start from here.

Condition: Here you need to provide the conditions for the loop to continue or exit. The compiler will check the condition and if it returns true then only further statements will be executed or else compiler will exit the for…loop.

Eg: for(k=0; k<10; increment/decrements) {

//’n’ Statements to be executed

}

Here the For…loop executes till k is less than 10.

increment / decrement : Here you can specify whether you want the compiler to increment the previously stored value or decrement the value

eg: for(k=0; k<10; k++) { //incrementing k by 1 after every iteration }

or for(k=10;k<0; k–) { //decrementing k by 1 after every iteration }

For…Loop Example

Let’s take an example of a for…loop

public static void main(String[] args)

{

for(int i=1;i<=5;i++)

{

System.out.println(i);

}

}

Output of this program would be as follows:

1

2

3

4

5

Flow diagram for For…Loop

To understand the for loop better, let’s have a look at the execution cycle:

Understanding Loops in Java

FOR…EACH LOOP

IF you want to traverse through each and every element of an array or collections in java then we can use for…each loop. Here we don’t need to increment / decrement any value as it works on the basis of elements and not on the basis of indexing (as it was in the for…loop).

In this case, each and every element in the array or collection are traversed and returned one by one.

Let’s look at the syntax of for each loop:

for (Type variable : array/collection)

{

//statement

}

 For…each loop example

Let’s take an example to understand the working of For…each loop

public class ForEachEg

{

public static void main(String[] args)

{

int arr[]={11,12,13,14,15};

for(int i:arr)

{

System.out.println(i);

}

}

}

Here arr[] is an integer array having 5 elements.

For(int i : arr) => this is the for each statement were each array element is traversed and saved in the integer variable i, one by one and is getting printed because of System.out.println(i) statement.

Output of this program will be as shown below:

11

12

13

14

15

WHILE… LOOP in Java

If you want to iterate a part of the program several times and if the iterations are not fixed then while loop is the good candidate.

Let’s look at the syntax of while loop:

 while(condition)

{

//statement to be executed

}

The flow diagram to understand the execution of While…loop is as shown below:

Loop Statements in Java

While…loop Example

Let’s take an example to understand the working of While…loop:

public class WhileEg {

public static void main(String[] args) {

int i=1;                        //initialization is outside the loop

while(i<=10){             //condition is in the while loop braces

System.out.println(i);  //printing the value of i

i++;                 //increment the variable

}

}

}

Output of this program will be as follows:

1

2

3

4

5

6

7

8

9

10

DO…WHILE LOOP

Do while loop is similar to while loop. However there is a minor difference between both of them.

Do – While, as the name suggest : If you WANT TO execute the loop at least once and then start checking the condition then you go for Do….While loop

Let’s look at the syntax of do…while loop:

 do

{

//code to be executed

}

while(condition);

To understand the execution process of a Do…While loop, let’s look at its flow diagram:

Loop Statements in Java

Do…While Loop Example

Let’s take an example to demonstrate the working of Do….While loop:

public class DoWhileExample {

public static void main(String[] args) {

int i=1;            //initialization

do{

System.out.println(i);  //print value of i

i++;     //increment the value of i by 1

}while(i<=10);            //condition to check

}

}

Output of this program will be as follows:

Output:

1

2

3

4

5

6

7

8

9

10

Conclusion

In this tutorial, we looked at three types of loop constructs used in Java. The For..loop is the standard loop even though it is slower than For..each loop as far as execution is concerned. However, the For…loop provides better flexibility.

The Do…while loop works as any other loop statement but provides an additional functionality of executing the logic in the loop at least once.

 

What’s Next?

This tutorial was on understanding loops in Java. This tutorial is part of our complete Java Tutorials for Selenium. We also have a series of Selenium Tutorials for beginners.

Are you looking to become an Automation tester in Selenium?

Techcanvass offers Automation Testing and Business Analysis certification courses. We are an IIBA endorsed education provider (EEP), iSQI Germany Authorised Training as well as Agile Testing alliance partner for CP-SAT certification training in Selenium.

One of the key features of our courses is the Job readiness package, as shown below:

Selenium Certification training with Job readiness
CP-SAT Certification Training