While, Do..While and For loop examples

Just like decision making statements, looping statements also execute the statements based on some condition but if we want to execute the same statement more than once with condition checking then we go for looping statements.

The following are the types of looping statements in Java: -

1. while loop
2. do..while loop
3. for loop

1. while loop:

while loop is the basic of all looping statements, which executes the loop repeatedly until the conditional expression evaluates to false.

Syntax:

while(boolean_expression){
statements;
}

Example:

package com.seleniumeasy.controlstatements;

public class WhileDemo {
	public static void main(String[] args) {
		int i=1;
		while(i<=10){
			 System.out.println(i);
			i++;// incrementing i value.
			
		}
	}
}

Here we are printing the same i value for 10 times but with different output that is doing same operation repetitively based on the condition. while loop will check the Boolean expression if it evaluates to true then statement inside while will executes and incremented the value and once again it goes to while loop and checks for the condition. this loop repeats until the conditional expression of while loop becomes false. once the condition becomes false it comes out of loop.

The conditional expression of while loop must be a Boolean type and if we try to give other than Boolean type like int or string it gives compile time error.

Example:

while(2)// this gives error
System.out.println("while loop");

There may be single statement or block of statements in while loop. if there is single statement then no need of braces and it should not be declarative statement but single statement for while loop are not useful.

Let us now look into while loop fir selenium and where we use while loop in selenium. There are many places where this 'while' loop is used when writing selenium tests like 'Reading data from properties file' , 'Reading data from excel files' and 'Retrieving values from database' etc.

The below is the sample code to read the data from properties file until it has completed reading the values from properties file, which is validated using 'KeyValues.hasMoreElements()'.
Check out for full example here read the data from properties file using while

while (KeyValues.hasMoreElements()) {
String key = (String) KeyValues.nextElement();
String value = prop.getProperty(key);
System.out.println(key + ":- " + value);
}

2.do..while loop:

while and do..while loops, both are same . the only difference is while loop checks the conditional expression first and if it is true then executes statement. where as do while first executes the statement then checks for the conditional expression.

Syntax:

do{
statements;
}while(boolean_expression);

Example:

package com.seleniumeasy.controlstatements;

public class DoWhileDemo {

	public static void main(String[] args) {
		int i=1;
		do{
			System.out.println(i);
			i++;
		}while(i<=10);
	}
}

Here in do while first it prints the i value for the first time and then check for condition and if it evaluates to true then statements inside do while loop will execute for second time and this process continuous untill the conditional expression truns to false once it evaluates to false then comes out of the loop.

In do..while loop where the conditional expression is true or false, statements in side loop will executes at-least for once.

3. for loop:

for loop is the famous and most commonly used loop in java programming.

Syntax:

for(initialization;boolean_expression;increment_decrement){
statements;
} 

In for loop, initializing the value, checking for condition and increment or decrement comes in single step.

Example:

package com.seleniumeasy.controlstatements;

public class ForLoopDemo {
	public static void main(String[] args) {
		for(int i=0;i<10;i++){
			System.out.println(i);
		}
	}
}

In the above program initialization part will execute first and only for once and next condition will be checked and if the condition is evaluated to true, statements inside for loop will be executed and then incrementation operation will be performed and once again now goes to checking for condition and if it evaluates to true statements executed this process will repeat until the conditional expression becomes false . once this becomes false it comes out of loop.

In the initialization part we can declare more than one value but it should be of same type
Example:

for(int i=1,j=1; i<10; j++)

for-each loop(enhanced for loop):
for-each loop is introduced in java 1.5v.
this loop is mainly used to retrieving the elements in array and collections

Syntax:

for(declaration:expression){
statements;
}

Example:

package com.seleniumeasy.controlstatements;

public class ForEachDemo {
	public static void main(String[] args) {
		int a[]={1,2,3,4,5,6,7,8,9,10};  
		   for(int i:a){  
		     System.out.println(i);  
		   }  
	}
}

Let us now use for-each loop in selenium in the blow example:

boolean flag = false;
		List<WebElement> listBoxItems = driver.findElements(By.tagName("li"));			            
		for(WebElement item : listBoxItems)
		{
			if(item.getText().equals(value))      		
				flag=true;
			break;
		}

In the above example, we are first getting the list of WebElements. driver.findElements statement returns list of webElements. Now from that list, first we will loop each element and get the text to compare with value. If the values is equal we will make the 'flag' to true. We use this at many places like ' Select a value from list, Selecting a desired date from calendar, 'To select a check from multiple checkboxes', where you list of items/elements and then do what ever you want once you find the one which you are looking for.

Java Tutorials for Selenium: 

Comments

How do we use for each loop while picking a date from Date calendar? First, we need to locate the calendar. Second, will perform click() on it to open it. Third, we will store all the dates in a list of webelements. Then, how do execute for each loop? Can you please tell me?

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.