1D Arrays
B2.2.2 - Construct programs that apply arrays and Lists. This page: one-dimensional (1D) arrays.
Key Concepts
An array stores a fixed number of values of the same type in contiguous memory. Each element is accessed by its index, starting at 0. (Python has no fixed-size array - its equivalent is the list, which grows and shrinks dynamically. Indexing works the same way.)
Declaration
// Declare with a fixed size - all elements default to 0
int[] scores = new int[5];
// Declare and initialise with known values
int[] scores = {85, 72, 91, 60, 78};
# Python lists grow dynamically - there is no fixed-size declaration.
# The twin of new int[5] is a pre-built list of five zeros:
scores = [0, 0, 0, 0, 0]
# Create a list with known values
scores = [85, 72, 91, 60, 78]
Access and Modification
System.out.println(scores[0]); // 85 - first element
System.out.println(scores[4]); // 78 - last element
scores[2] = 95; // modify an element
print(scores[0]) # 85 - first element
print(scores[4]) # 78 - last element
scores[2] = 95 # modify an element
Array Length
System.out.println(scores.length); // 5 - note: no parentheses, it's a property
print(len(scores)) # 5 - len() works on lists AND strings, no .length trap in Python
lengthis a field (no parentheses), not a method. Writingscores.length()is a compile error. Compare withString:str.length()uses parentheses because it is a method call.
Traversal
The standard pattern to visit every element:
for (int i = 0; i < scores.length; i++) {
System.out.println("scores[" + i + "] = " + scores[i]);
}
for i in range(len(scores)):
print("scores[" + str(i) + "] = " + str(scores[i]))
Index
iruns from0toscores.length - 1. Accessingscores[scores.length]causes anArrayIndexOutOfBoundsException.
Visual Layout
Worked Examples
Example 1: Find Maximum
Start by assuming the first element is the largest, then compare against every other element.
int[] numbers = {34, 67, 12, 89, 45};
int max = numbers[0]; // assume first element is the largest
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum: " + max); // Maximum: 89
numbers = [34, 67, 12, 89, 45]
# max is a built-in function name in Python, so we call it largest
largest = numbers[0] # assume first element is the largest
for i in range(1, len(numbers)):
if numbers[i] > largest:
largest = numbers[i]
print("Maximum:", largest) # Maximum: 89
The loop starts at index 1 because index 0 is already our initial guess. The same pattern works for minimum - just flip > to <.
Example 2: Sum and Average
int[] numbers = {34, 67, 12, 89, 45};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
double average = (double) sum / numbers.length;
System.out.println("Sum: " + sum + ", Average: " + average);
// Sum: 247, Average: 49.4
numbers = [34, 67, 12, 89, 45]
# sum is a built-in function name in Python, so we call it total
total = 0
for i in range(len(numbers)):
total = total + numbers[i]
average = total / len(numbers) # / always gives a decimal in Python - no cast needed
print("Sum: " + str(total) + ", Average: " + str(average))
# Sum: 247, Average: 49.4
The (double) cast is essential - without it, integer division would truncate the result. 247 / 5 gives 49 in integer arithmetic, but 247.0 / 5 gives 49.4.
Example 3: Count Occurrences
int[] numbers = {34, 67, 12, 67, 45};
int target = 67;
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
count++;
}
}
System.out.println(target + " appears " + count + " time(s).");
// 67 appears 2 time(s).
numbers = [34, 67, 12, 67, 45]
target = 67
count = 0
for i in range(len(numbers)):
if numbers[i] == target:
count = count + 1
print(str(target) + " appears " + str(count) + " time(s).")
# 67 appears 2 time(s).
Example 4: Copying Arrays (The Reference Trap)
Arrays in Java are objects. Assigning one array to another copies the reference, not the data.
// WRONG - both variables point to the same array
int[] original = {1, 2, 3, 4, 5};
int[] copy = original;
copy[0] = 99;
System.out.println(original[0]); // 99 - original changed too!
# WRONG - both variables point to the same list (Python lists are references too)
original = [1, 2, 3, 4, 5]
copy = original
copy[0] = 99
print(original[0]) # 99 - original changed too!
The correct way - element-by-element copy:
int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[original.length];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i];
}
copy[0] = 99;
System.out.println(original[0]); // 1 - original is untouched
original = [1, 2, 3, 4, 5]
copy = [] # start empty - Python lists grow with append()
for i in range(len(original)):
copy.append(original[i])
copy[0] = 99
print(original[0]) # 1 - original is untouched
Assigning one array variable to another copies the reference. To create an independent array in these examples, allocate a new array and copy the elements individually.
Example 5: Resizing an Array
Arrays have a fixed size. To “grow” an array, create a larger one and copy the data across:
int[] data = {10, 20, 30};
// Step 1: Create a larger array
int[] temp = new int[data.length + 2];
// Step 2: Copy elements
for (int i = 0; i < data.length; i++) {
temp[i] = data[i];
}
// Step 3: Reassign the reference
data = temp;
System.out.println(data.length); // 5
data = [10, 20, 30]
# Python lists grow dynamically, so the manual resize pattern is not needed.
# Appending two extra slots gives the same result as Java's copy-and-grow:
data.append(0)
data.append(0)
print(len(data)) # 5
This is the idea
ArrayListuses internally: when its array is full, it makes a larger one and copies the data across. It makes the new array about one and a half times bigger, so it does not have to copy on every add. Doing it by hand here shows what that costs.
Example 6: Duplicate Detection
Compare every pair using nested loops:
int[] numbers = {34, 67, 12, 67, 45};
boolean duplicateFound = false;
for (int i = 0; i < numbers.length - 1 && !duplicateFound; i++) {
for (int j = i + 1; j < numbers.length && !duplicateFound; j++) {
if (numbers[i] == numbers[j]) {
duplicateFound = true;
System.out.println("Duplicate found: " + numbers[i]
+ " at index " + i + " and index " + j);
}
}
}
// Duplicate found: 67 at index 1 and index 3
numbers = [34, 67, 12, 67, 45]
duplicate_found = False
# while loops keep the early-exit check in the loop condition (no break needed)
i = 0
while i < len(numbers) - 1 and duplicate_found == False:
j = i + 1
while j < len(numbers) and duplicate_found == False:
if numbers[i] == numbers[j]:
duplicate_found = True
print("Duplicate found: " + str(numbers[i])
+ " at index " + str(i) + " and index " + str(j))
j = j + 1
i = i + 1
# Duplicate found: 67 at index 1 and index 3
The && !duplicateFound condition provides an early exit - no point continuing once a match is found.
Quick Check
Q1. Given int[] arr = new int[6], what is the last valid index?
Q2. After int[] b = a; b[0] = 99; - what is a[0]?
Q3. What is arr[0] after int[] arr = new int[4];?
Q4. Which is the correct way to get the size of an array arr?
Q5. What happens when this code runs?
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
} Q6. Why does the find-maximum algorithm initialise max = numbers[0] instead of max = 0?
Trace Exercise
Trace this code that finds the maximum value in an array. Fill in the value of numbers[i] and max after each comparison.
int[] numbers = {34, 67, 12, 89, 45};
int max = numbers[0]; // max = 34
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum: " + max);
numbers = [34, 67, 12, 89, 45]
largest = numbers[0] # largest = 34 (max is a built-in name in Python)
for i in range(1, len(numbers)):
if numbers[i] > largest:
largest = numbers[i]
print("Maximum:", largest)
| i | numbers[i] | numbers[i] > max? | max after |
|---|---|---|---|
| - | - | - | (initial) |
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
Final output: Maximum:
Code Completion
Complete the code that creates a reversed copy of an array without modifying the original.
This algorithm maps each element from the original array to its mirror position in a new array. Fill in the blanks to complete the reversed copy:
int[] original = {1, 2, 3, 4, 5};
int[] reversed = new int[];
for (int i = 0; i < original.length; i++) {
reversed[] = original[i];
}
System.out.println(reversed[0]); // prints
Spot the Error
This code attempts to create an independent copy of an array so the original stays unchanged, but it falls into Java's reference-vs-value trap - modifying the "copy" also changes the original. Select the buggy line, then pick the fix.
Pick the correct fix for line 5:
Option (a) creates a new array but never copies the data, so every element would be 0. Option (b) creates a new array and then throws it away: the second statement points
copyback at the original array, so both names still share one array. Option (c) is the loop copy you should be able to write yourself. (original.clone()andArrays.copyOf(original, original.length)also make a real, independent copy.)
Predict the Output
This code demonstrates the accumulator pattern - it traverses an array and builds a running total by adding each element to a sum variable. What is the exact output?
int[] arr = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
System.out.println("Sum: " + sum);Type your answer:
Practice Exercises
Core
-
Input and Print - Write code in
mainthat creates an array of 5 integers with the values{8, 3, 15, 7, 12}. Print each element on its own line with its index (e.g.,[0] = 8). -
Find Minimum - Given
int[] temps = {22, 18, 25, 15, 20}, find and print the minimum value and the index where it occurs. -
Count Above Threshold - Given
int[] scores = {72, 85, 60, 91, 45, 78}, count and print how many scores are 70 or above. -
Sum of Even Elements - Given an array of integers, calculate and print the sum of only the even values.
Extension
-
Reverse Copy - Create a reversed copy of
{1, 2, 3, 4, 5}without modifying the original. Print both arrays to verify. -
Remove Duplicates - Given
{3, 7, 3, 2, 7, 5, 2}, create a new array containing only the unique values (in order of first appearance). Print the result.
Challenge
- Resize and Insert - Given
int[] data = {10, 20, 30, 40, 50}, write code that creates a new array one element larger, inserts the value25at index 2, and shifts the remaining elements right. The result should be{10, 20, 25, 30, 40, 50}.
GitHub Classroom
A class assignment on GitHub Classroom: use it when your teacher has set it. It needs a free GitHub account.
Working in the Codespace
- Accept and open. Accept the assignment above, open the link in the email from GitHub, then press Open in Codespace. In Java, change the status bar from Lightweight to Standard mode.
- Write and check. Open
src/ArraysCore.javaand complete eachTODO. Open src/ArraysCore.java first, implement the TODOs, then run ./run-tests.sh in the Codespaces Terminal. Press Run and compare the output with the comments, or runbash run-tests.shin the Terminal. - Submit. In Source Control, write a message, press Commit, then Sync Changes. Your teacher’s feedback arrives as a pull request called Feedback.