Difficulty: Beginner to Intermediate | Prerequisites: Basic Java syntax, loops, primitive data types
Arrays and ArrayLists are the first data structures most Java programmers encounter. They let you store and work with collections of values rather than juggling dozens of individual variables. Arrays are fixed in size and fast; ArrayLists are flexible and grow as needed. Understanding both, and knowing when to reach for each, is foundational for every topic that follows in this course, from sorting algorithms to object-oriented design.
Arrays hold a fixed number of elements of the same type, accessed by index starting at 0. ArrayLists do the same thing but can grow and shrink dynamically, and they only store objects (not primitives). Java handles the primitive-to-object conversion automatically through autoboxing.
Array
A fixed-length, ordered collection of elements that all share the same data type. Think of it as a row of numbered slots, each holding one value.
Index
The position number of an element inside an array, starting at 0. In simple terms, the slot number you use to look up or set a value.
.length (array property)
A public instance variable (not a method) that returns how many slots the array has. No parentheses: values.length, not values.length().
Partially filled array
An array allocated at some maximum size where only some of the slots are actually in use. You track how many are filled with a companion variable, typically called currentSize.
For-each loop (enhanced for loop)
A loop that iterates over every element in an array or collection without using an index counter. Convenient for reading values, but you cannot modify the array contents or access a specific index position with it.
ArrayList
A resizable list from java.util that stores objects and provides methods for adding, removing, and searching elements. Think of it as an array that can grow and shrink on its own.
Wrapper class
An object version of a primitive type: Integer for int, Double for double, Boolean for boolean, Character for char. Required because ArrayLists can only hold objects.
Autoboxing
Java's automatic conversion between a primitive value and its corresponding wrapper class. If you add a plain int to an ArrayList, Java wraps it for you.
Two-dimensional array (2D array / matrix)
An array of arrays, arranged in rows and columns. Declared with two sets of brackets: int[][] grid = new int[rows][cols];.
Declare with the type and square brackets: double[] values;
Initialise with new and a size: double[] values = new double[10];
Shorthand initialisation with values: int[] primes = {2, 3, 5, 7, 11};
Default values on creation:
Numbers: 0
Booleans: false
Object references: null
Once created, the length of an array cannot change.
Use the index in square brackets: values[4] = 35;
Valid indices for an array of size n run from 0 to n - 1.
An array declared as nums[10] has indices 0 through 9.
Array elements behave like any other variable: System.out.println(values[4]);
Standard for loop when you need the index:
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
For-each loop when you just need each value:
for (double element : values) {
total = total + element;
}
You cannot use a for-each loop to change stored values or to find the index of a specific element.
Allocate a maximum size, then track actual usage with a companion variable (currentSize).
Only process elements from index 0 to currentSize - 1.
Import required: import java.util.ArrayList;
Declaration: ArrayList
Only stores object types, not primitives. Use wrapper classes (Integer, Double, etc.) for numeric data.
add(element) – appends to the end.
add(index, element) – inserts at the given index; shifts everything after it one position to the right.
size() – returns the number of elements (starts counting at 1, so a list with three items returns 3).
get(index) – returns the element at the given index.
set(index, element) – replaces the element at the given index.
remove(index) – removes the element at that index, shifts everything left, decreases size by 1, and returns the removed value. This is a mutator method.
remove(new Integer(value)) – removes by value rather than by index when dealing with integers. You must wrap the value in an Integer object, otherwise Java interprets the number as an index.
indexOf(element) – returns the index of the first occurrence, or -1 if not found.
contains(element) – returns true if the element is present, false otherwise.
clear() – empties the list.
remove, indexOf, and contains rely on the element's .equals() method. They only work correctly if the stored type defines one (Strings do by default).
for (String name : names) {
System.out.println(name);
}
This is equivalent to:
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
System.out.println(name);
}
Declaration: int[][] counts = new int[COUNTRIES][MEDALS];
Access with two indices: counts[r][c]
Number of rows: counts.length
Number of columns in a given row: counts[r].length
Use nested loops to traverse:
for (int r = 0; r < counts.length; r++) {
for (int c = 0; c < counts[r].length; c++) {
System.out.printf("%8d", counts[r][c]);
}
System.out.println();
}
Task | Syntax |
|---|---|
Declare array |
|
Create array |
|
Inline initialise |
|
Array length |
|
Create ArrayList |
|
ArrayList size |
|
2D array creation |
|
Row count (2D) |
|
Column count (2D) |
|
Arrays underpin almost every data-heavy program: image pixels are stored in 2D arrays, audio samples sit in arrays of doubles, and leaderboards are arrays sorted by score. ArrayLists power any list that changes size at runtime, from a shopping cart to a social media feed.
Students often think .length on an array uses parentheses like a method call. It does not. It is a public instance variable: values.length, not values.length().
Students assume they can resize an array after creation. You cannot. If you need a resizable collection, use an ArrayList.
Calling remove(12) on an ArrayList removes the element at index 12, not the element whose value is 12. To remove by value, wrap it: remove(new Integer(12)).
Students forget that indexOf, contains, and remove (by value) depend on the .equals() method. If your stored type does not override .equals(), these methods will not behave as expected.
⚠️ Know the difference between .length (array, no parentheses) and .size() (ArrayList, with parentheses). This is a classic exam question.
⚠️ Be able to trace through a for-each loop and a standard for loop and identify when each is appropriate.
⚠️ Understand autoboxing and why ArrayList is invalid (must use ArrayList).
⚠️ Expect questions on partially filled arrays and the role of the currentSize companion variable.
⚠️ 2D array traversal with nested loops appears frequently on exams. Know how to get row count vs. column count.
True or False: An array's .length is a method call that requires parentheses.
False. It is a public instance variable, no parentheses.
Fill in the blank: The default value of an uninitialised boolean array element is _______.
false
True or False: You can use a for-each loop to change the values stored in an array.
False. The loop variable is a copy; changes to it do not affect the array.
Fill in the blank: To remove the Integer value 12 (not the element at index 12) from an ArrayList, you write list.remove(__________).
new Integer(12)
Q: What is the valid index range for an array declared as int[] data = new int[5];?
A: 0 through 4 (inclusive).
Q: Why must you use wrapper classes like Integer instead of int when creating an ArrayList?
A: ArrayLists can only store objects, not primitive types. Wrapper classes provide the object version of each primitive.
Q: Write a for-each loop that calculates the sum of all elements in a double[] array called scores.
A:
double total = 0;
for (double s : scores) {
total = total + s;
}
Q: In a 2D array called matrix, how do you obtain the number of columns in the third row?
A: matrix[2].length
Q: What does ray.indexOf("c") return if "c" is not in the ArrayList?
A: It returns -1.
This material connects directly to Chapter 8 (Designing Classes), where arrays and ArrayLists appear as instance variables inside custom classes. Sorting and searching algorithms (later in most CS curricula) operate on arrays. The Comparable interface (Chapter 10) is used to define ordering for elements stored in arrays and ArrayLists.
array, ArrayList, Java arrays, Java ArrayList, fixed-size collection, dynamic list, index, zero-indexed, .length, .size(), for-each loop, enhanced for loop, partially filled array, currentSize, wrapper class, Integer, Double, Boolean, Character, autoboxing, auto-boxing, unboxing, 2D array, two-dimensional array, matrix, nested loop, java.util.ArrayList, remove, indexOf, contains, get, set, add, clear, COMP SCI, Texas A&M, intro to programming