while and for
A loop is how one line of logic handles a million rows: apply the tax rule to every order, check every password attempt, sum every sensor reading. Without loops you would copy-paste the same statement per item, which is exactly what early programmers did until loops were invented. while is Python's while with parentheses and braces. The classic for packs setup, condition, and step into one line:
for (int i = 0; i < 5; i++) { System.out.println(i); }
Read it as: start i at 0, keep looping while i < 5, add 1 after each pass. It prints 0 through 4, exactly like Python's for i in range(5). break and continue work the same as in Python.
Arrays
An array is Java's fixed-size list. Its type is the element type plus []:
int[] scores = {90, 72, 88}; scores[0] // 90 scores.length // 3 (no parentheses!) scores[1] = 75; // arrays are mutable
Unlike a Python list, an array cannot grow or shrink, and every element has the same declared type. To visit each element, Java has the enhanced for loop, its version of for x in list:
for (int s : scores) { System.out.println(s); }
Read : as "in". You get each element in order, without managing an index.
Code exercise · java
Run this: a classic for printing a countdown, then an enhanced for summing an array.
Off by one: the classic loop bug
Array indexes run from 0 to length - 1. Ask for scores[3] on a 3-element array and the program throws an ArrayIndexOutOfBoundsException at runtime — the compiler cannot catch it, because the index might be computed from data it cannot predict. This is why the classic for-loop idiom is always i < scores.length, never i <= scores.length: the <= version runs one extra pass and dies on the last one. When a loop crashes, check the boundary first — it is the most common loop bug in any language.
Quiz
How do you get the number of elements in an array called data, and the length of a String called s?
Code exercise · java
Your turn. Using a classic for loop from 1 to 10, add up only the even numbers (use % from lesson 3-1) and print `even sum: 30`. Then use an enhanced for to find the largest value in the prices array and print `max: 9.5`.
Code exercise · java
Your turn. Find the largest value in the temps array. Start max at temps[0], sweep with an enhanced for, and update max whenever you see something bigger. Print exactly `max: 79`.