Java Notes
A for loop repeats code a known number of times or visits every value in an array, such as every mark in a list.
A loop repeats work. Use a for loop when you know how many times the work should repeat, or when you need to visit each item in a list.
For example, showing lessons 1 to 5, printing marks in an array, or adding all marks together are repetition tasks. Without a loop, you would write nearly the same line many times.
Traditional for loop: repeat with a counter
A traditional for loop has three parts inside its brackets:
for (start; continue while this is true; change after each round)
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Read the loop one part at a time:
int lesson = 1creates a counter and gives it the starting value 1. This runs once.lesson <= 5is the question Java checks before every round. The loop continues while it is true.- The code inside
{ }runs and prints the current lesson number. lesson++adds 1 after the round finishes.- Java checks the condition again. When
lessonbecomes 6,6 <= 5is false and the loop stops.
Change the start, end, or lesson++ part one at a time, then run the program. This is the fastest way to understand how a loop moves.
Count up, count down, and skip values
The counter does not have to start at 1 or add 1 every time. You choose the values that match the task.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
In the first loop, number-- subtracts 1 after each round, so Java counts down. In the second loop, number += 2 adds 2, so only even numbers appear. Always make sure the update moves the counter toward a point where the condition becomes false; otherwise the loop may never end.
Visit an array by index
An array holds several values. Each value has a position called an index. Java starts array indexes at 0, not 1.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
marks.length is the number of items in the array: 3. The valid indexes are therefore 0, 1, and 2. marks[index] gets the value at the current position. We print index + 1 only to show people Mark 1, Mark 2, and Mark 3.
Use an index loop when you need the position, want to print a numbered list, or need to replace a value at a particular position.
The common array-loop mistake
Do not write index <= marks.length. When the array has 3 items, marks.length is 3, but index 3 does not exist. This causes ArrayIndexOutOfBoundsException.
The safe condition is always index < marks.length.
For-each loop: visit values when positions do not matter
Use a for-each loop when you only need every value and do not need its index. Read for (int mark : marks) as: “for every mark inside marks.”
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The loop gives mark the first value (72), then the next (81), then the final value (94). Each round adds the current mark to total. The loop stops automatically after the last array value.
For-each is shorter and safer for reading every value. Use the index form when you need to know *where* a value is or need to change marks[index].
Common for-loop mistakes
- A condition that is always true creates an infinite loop, such as
for (int i = 1; i >= 1; i++). - Forgetting the update part, such as
i++, often makes the loop never end. - Starting an array index at 1 skips the first value because arrays start at 0.
- Using
<= array.lengthgoes one index too far.
When a loop behaves strangely, print the counter inside the loop. Seeing its values tells you whether the start, condition, or update is wrong.
Try it yourself
Create a class named MultiplesOfThree. Use a for loop to print all numbers from 1 through 20 that are divisible by 3. Then calculate their total.
Hint
Use % to check a remainder. number % 3 == 0 is true only when a number divides exactly by 3. Create int total = 0; before the loop and add matching numbers inside it.
One working answer
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Run it, then change the end from 20 to 30. Check that the loop finds more multiples and the total changes.
Continue the lesson path