Source: CS 101, Intro to Computer Science, UIUC
Tags: Java arrays, for loop, while loop, enhanced for loop, for-each loop, array indexing, 0-indexed, .length, array algorithms, sum array, find maximum, loop initialization, loop condition, loop update
Difficulty: Beginner to Intermediate | Prerequisites: Java Variables and Types (Lectures 1 & 2), Comparisons and Conditionals (Lecture 3). You need to be comfortable with variable declaration, assignment, and boolean expressions.
Arrays and loops are where Java programs start doing real work. An array lets you store a whole collection of values under one name, and a loop lets you process every element in that collection without writing separate code for each one. Together, they are the foundation for algorithms: searching, summing, finding a maximum, sorting. Nearly every non-trivial program combines arrays and loops in some form, so this is the material that bridges "I can store a number" to "I can solve a problem."
A Java array is a fixed-size, ordered collection of values of the same type, accessed by a zero-based index. Loops (while and for) repeat a block of code until a condition becomes false. Combining loops with arrays lets you iterate over every element to do things like print all values, compute a sum, or find the largest item.
Array
An ordered, fixed-size collection of values that share the same type. Declared with brackets: int[] myArray;
Think of it as a row of numbered boxes, all the same shape, where the first box is number 0.
Index
The position of a value within an array. Java arrays are 0-indexed, meaning the first element is at position 0.
In simple terms, the address of a specific slot in the array.
0-indexing
The convention that the first element of an array is at index 0, the second at index 1, and so on. The last element is at index array.length - 1.
.length
A property of every Java array that returns the number of elements it holds. Not a method (no parentheses).
In simple terms, it tells you how many slots the array has.
Array initialisation
The process of creating an array and (optionally) filling it with values. Two common forms:
int[] a = new int[8]; creates an array of 8 integers, all initially 0
int[] a = {1, 2, 5, 10}; creates and fills in one step
while loop
A control structure that repeats a block of code for as long as its condition is true.
Think of it as "keep doing this until the condition says stop."
for loop
A compact loop that bundles initialisation, condition, and update into a single line: for (init; condition; update) { ... }
In simple terms, a tidier way to write the same logic as a while loop when you know the pattern upfront.
Enhanced for loop (for-each)
A shorthand for iterating over every element of an array without managing an index variable: for (int x : array) { ... }
Think of it as "for each element in this array, do something with it."
Loop initialisation
The setup step that runs once before the loop begins. In a for loop, this is the first part: int i = 0.
Loop condition
The boolean expression checked before every iteration (including the first). The loop stops when this is false.
Loop update
The step that runs after each iteration and before the next condition check. Typically increments or decrements the counter: i++.
Use brackets after the type to declare an array:
int single; declares a single integer
int[] multiple; declares an array of integers
Two ways to initialise:
Specify a size: int[] multiple = new int[8]; (all elements default to 0)
Provide values: int[] multiple = {1, 2, 5, 10};
Once created, the size of an array cannot change
Works for any type: char[] awesome = {'c', 's', '!'};
Use bracket syntax with the index: array[index]
Arrays are 0-indexed:
First element: array[0]
Last element: array[array.length - 1]
Example:
int[] twos = {1, 2, 4};
System.out.println(twos[0]); // prints 1
twos[0] = 2; // changes first value to 2
System.out.println(twos[0]); // prints 2
System.out.println(twos[2]); // prints 4
System.out.println(twos[twos.length - 1]); // prints 4
Every array has .length, which returns its size
No parentheses (it is a property, not a method)
int[] multiple = new int[8];
System.out.println(multiple.length); // prints 8
A while loop repeats as long as its condition is true:
int index = 0;
while (index < 4) {
System.out.println(index);
index++;
}
Output: 0, 1, 2, 3
The three pieces of a loop:
Initialisation: int index = 0 (runs once)
Condition: index < 4 (checked before every iteration, including the first)
Update: index++ (runs after each iteration, before the next condition check)
A for loop packs the same three pieces into one line:
for (int index = 0; index < 4; index++) {
// do something
}
This is functionally identical to the while loop above.
When you want to visit every element and do not need the index, use the enhanced for:
int[] primes = {2, 3, 5, 7, 11, 13};
for (int prime : primes) {
System.out.println(prime);
}
This prints each value in the array. You cannot use this form to modify elements by index or to skip elements.
Printing all values:
char[] toPrint = {'a', 'b', 'c', 'd'};
for (int i = 0; i < toPrint.length; i++) {
System.out.println(toPrint[i]);
}
Summing an array:
int[] toSum = {10, 20, 30, 40, 50};
int sum = 0;
for (int current : toSum) {
sum += current;
}
System.out.println(sum); // prints 150
The pattern: start an accumulator at 0, then add each element.
Running sum (showing intermediate totals):
int[] toSum = {10, 20, 30, 40, 50};
int sum = 0;
for (int current : toSum) {
sum += current;
System.out.println(current + " " + sum);
}
System.out.println(sum);
Output: 10 10, 20 30, 30 60, 40 100, 50 150, 150
Finding the maximum of three values (using if/else if):
int first = 10;
int second = 15;
int third = 4;
if (first >= second && first >= third) {
System.out.println(first);
} else if (second >= first && second >= third) {
System.out.println(second);
} else if (third >= first && third >= second) {
System.out.println(third);
}
Output: 15
Array index range:
Valid indices: 0 to array.length - 1
For loop structure:
for (initialisation; condition; update) {
// body
}
Execution order: initialisation (once) → condition check → body → update → condition check → body → update → ... until condition is false.
Sum pattern:
accumulator = 0
for each element in array:
accumulator += element
Arrays and loops are behind any situation where software processes a list of things: calculating the average temperature over a week, iterating through a shopping cart to compute a total, scanning a list of sensor readings for the highest value. The sum-and-accumulator pattern you see here is the same logic that runs inside a spreadsheet's SUM function.
Students often try to access array[array.length], which is one past the end. The last valid index is array.length - 1. Going out of bounds throws an ArrayIndexOutOfBoundsException.
Students sometimes think while(true) loops will always run forever. They can be exited with a break statement or by a condition that changes within the loop body.
Students confuse the standard for loop's index variable with the element variable in the enhanced for loop. In for (int i = 0; ...), i is the index. In for (int x : array), x is the value at each position.
Students occasionally forget index++ inside a while loop, causing an infinite loop. The for loop structure helps prevent this by putting the update in the loop header.
⚠️ Know that arrays are 0-indexed. Be ready to trace through code that accesses array[0] and array[array.length - 1].
⚠️ Be able to convert between a while loop and a for loop, and explain why they are equivalent.
⚠️ The sum/accumulator pattern (initialise to 0, loop, add each element) is a staple exam question.
⚠️ Understand when to use a standard for loop (need the index) vs an enhanced for loop (just need the values).
⚠️ Be able to trace through nested logic: a loop containing an if statement, as in the find-maximum example.
True or False: The first element of a Java array is at index 1. False. It is at index 0.
Fill in the blank: To get the number of elements in an array a, you use a.______. Answer: length
True or False: int[] a = new int[5]; creates an array whose valid indices are 0 through 5. False. Valid indices are 0 through 4.
True or False: A for loop and a while loop can always express the same logic. True.
Fill in the blank: In a for loop, the update step runs _____ each iteration and _____ the next condition check. Answer: after, before
Q: What is the output of this code?
int[] nums = {5, 10, 15};
System.out.println(nums[nums.length - 1]);
A: 15. nums.length is 3, so nums[2] is the last element.
Q: Rewrite this while loop as a for loop.
int i = 0;
while (i < 3) {
System.out.println(i);
i++;
}
A:
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
Q: What value does sum hold after this code runs?
int[] values = {2, 4, 6, 8};
int sum = 0;
for (int v : values) {
sum += v;
}
A: 20. The sum of 2 + 4 + 6 + 8 = 20.
Q: Why does array[array.length] cause an error?
A: Because array indices run from 0 to array.length - 1. Index array.length is one position past the last element, which does not exist. Java throws an ArrayIndexOutOfBoundsException.
Q: Write code that prints the largest value in an integer array called data.
A:
int max = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
System.out.println(max);
Arrays and loops rely on the variable and type concepts from Lectures 1 and 2 (every array element has a type, every loop counter is a variable) and the boolean logic from Lecture 3 (the loop condition is a boolean expression). From here, the course will build toward more complex data structures and algorithms, where the patterns introduced here (iteration, accumulation, conditional checks inside loops) reappear constantly.
Java arrays, array declaration, array initialisation, 0-indexed, zero indexing, .length property, while loop Java, for loop Java, enhanced for loop, for-each loop, array iteration, sum array, find max in array, accumulator pattern, ArrayIndexOutOfBoundsException, loop counter, CS 101 UIUC, Java control flow, array algorithms