For loop is used in programming
A for loop is used in programming when you want to repeat a block of code a specific number of times or iterate through a collection such as an array or list.
1. Basic for loop in Java
for (int i = 0; i < 5; i++) { System.out.println(i); }
Output:
0 1 2 3 4
How it works
for (initialization; condition; increment) { // code to execute }
| Part | Example | Purpose |
|---|---|---|
| Initialization | int i = 0 | Creates and initializes the counter |
| Condition | i < 5 | Determines whether the loop continues |
| Increment | i++ | Increases the counter after each iteration |
The execution happens like this:
i = 0 → 0 < 5 → print 0 → i++ i = 1 → 1 < 5 → print 1 → i++ i = 2 → 2 < 5 → print 2 → i++ i = 3 → 3 < 5 → print 3 → i++ i = 4 → 4 < 5 → print 4 → i++ i = 5 → 5 < 5 → STOP
2. for loop with an array
This is very common in Selenium/Java QA automation:
String[] browsers = {"Chrome", "Firefox", "Edge"}; for (int i = 0; i < browsers.length; i++) { System.out.println(browsers[i]); }
Output:
Chrome Firefox Edge
3. Enhanced for loop
Java also provides a simpler for-each loop:
String[] browsers = {"Chrome", "Firefox", "Edge"}; for (String browser : browsers) { System.out.println(browser); }
Here:
String browser
represents the current element, and:
: browsers
means "take each element from the browsers array."
4. QA/Selenium example
Suppose you want to test several URLs:
String[] urls = { "https://example.com", "https://google.com", "https://yahoo.com" }; for (String url : urls) { driver.get(url); System.out.println("Testing: " + url); }
The browser will navigate to each URL one at a time.
Interview answer:
What is a for loop?
Answer: A for loop in Java is a control-flow statement used to repeatedly execute a block of code based on a condition. It typically consists of initialization, condition, and increment/decrement. It is commonly used when we know how many times we need to execute the code or when iterating through arrays and collections.
Important: i++ means increase i by 1, while i-- means decrease i by 1.

