Understanding Loops in Java | Java Tutorials for Selenium

Understanding Loops in Java

In the second part of this Java tutorial on control statements, we will have a detailed look at the loop statements. The loop constructs like while…. and For… are used in java to write logic for multiple iterations.

Read Also: Control Statements in Java

This java tutorial is part of Free Selenium 3.0 Tutorials by Techcanvass. These tutorials are categorized into Java, Selenium, TestNG, Automation Framework and Grid.

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:

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

eg: k = 0; => Here variable k is been initialized 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/decrement) {

//’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.

This tutorial was part of the Java tutorial for selenium.

About Techcanvass

Techcanvass offers IT certification courses for professionals. We are an IIBA endorsed education provider (EEP), iSQI ATP (for Certified Agile Business Analyst Training) as well as Agile Testing alliance partner for CP-SAT certification training in Selenium.

Our Selenium 3.0 Training programs along with DevOps courses are designed for Manual testing professionals with basics of Java and Python covered.

Selenium 3.0 Training with Java

Selenium Training Course

Selenium 3.0 Training with Python

python selenium training

Selenium Certification Training (CP-SAT)

Selenium Certification Course

DevOps Certification Training

DevOps Certification Training

 

Leave a Reply

Your email address will not be published. Required fields are marked *