MainMenu

Home Core Java Overview Maven Tutorials

Saturday, 3 March 2018

for each loop in java with example


for Each loop in java :
Hi all, in this demo i will describe about for-each loop in java.

This loop is important for selenium as well as for interview also.
So as the name says when we want to perform some operation with each element of the list or collection or array, then we use this loop.
The Syntax of the loop is :
for(data_type variable_name : array|collection)
{
}
it will get more clear when we describe it through an example :

Example of for-each loop in java


public class foreach
{
public static void main(String args[])
{
int arr[] = {10, 20, 30, 44};
for(int x : arr)
{
System.out.println("Your number is :" + x);
}
}
}
---------------------------------------------------------------------------
Now, Suppose you are working in some selenium project, and have create a WebElement list then, you can perform operation with each element using for -each loop

For Each Loop in selenium Example :
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class foreach_selenium
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void h()
{
List list = driver.findElements(By.cssSelector("#post-body-751561208295527719>div>div>table>tbody>tr>td>a"));
System.out.println("Your total list elements are :" +list.size());
for(WebElement wb : list)
{
System.out.println(wb.getText());
}
}
}


Output :

Manual Testings Introduction
Definitions of Manual Testings
Defect Clustering in Software Testing
Bug Life Cycle & Reviews
Level of Testing
TEST CASE, TEST PLAN & RTM
Manual test Cases for Pen
Manual test cases for Email
ISTQB Practice set
Important Unix Command for Software Tester
Testings Myth
Agile Methodology
Windows & Linux Shortcut keys
Test Strategy in Software Testing
Finance Testing Basics
Mobile Test
Effort Estimation Technique
Java Script Basics
How to test Login page & Date fields manually
Technical Tips
Function in Javascript
Discussion Forum
Download e_Books
Professional Ethics
Aptitude Tricks
English Speaking Tutorials

1 comment:

  1. This is helpful. Can you also please tell me how to select each item in a drop down and do actions for example. to create an account there are 3 account types in the account type drop down. Only one page differs in the account types all the other pages remains the same. I want to select each account type one by one create an account with each.

    ReplyDelete