Your test case says: 'If the user is new, expect the welcome banner; otherwise skip to step 4. Repeat for each browser.'
if/else is the 'if…otherwise'. Loops are the 'repeat for each'. You've been writing control flow in English for years.
int statusCode = 404; if (statusCode == 200) { System.out.println("PASS: page loaded"); } else if (statusCode == 404) { System.out.println("FAIL: page not found"); } else { System.out.println("FAIL: unexpected status " + statusCode); }
FAIL: page not found
Conditions are boolean expressions built from comparisons: ==, !=, >, <, >=, <=, combined with && (and), || (or), ! (not). Note == is fine for numbers and booleans — the String rule from last lesson still stands.
The for-each loop reads almost like your test case's own language:
String[] browsers = {"chrome", "firefox", "edge"}; for (String browser : browsers) { // "for each browser in browsers" System.out.println("Running smoke test on " + browser); } // classic counted loop — when you need the index or a count: for (int attempt = 1; attempt <= 3; attempt++) { System.out.println("Login attempt " + attempt); }
Running smoke test on chrome Running smoke test on firefox Running smoke test on edge Login attempt 1 Login attempt 2 Login attempt 3
This is why automation scales: the loop that checks 3 browsers checks 300 data rows with the same four lines. Repetition is free for machines and expensive for humans — loops are where you cash that in.
while loop repeats until a condition turns false — useful, but a loop waiting for a page that never loads runs forever. Real frameworks use timeouts for exactly this reason; you'll meet WebDriverWait in Suite 04, which is a while-loop-with-a-deadline done right.Given int[] codes = {200, 200, 404, 200, 500}; write (on paper or in a scratch file) a loop that prints PASS for each 200 and FAIL: <code> otherwise, then prints the total number of failures at the end.
int[] codes = {200, 200, 404, 200, 500}; int failures = 0; for (int code : codes) { if (code == 200) { System.out.println("PASS"); } else { System.out.println("FAIL: " + code); failures++; } } System.out.println("Total failures: " + failures);