Difficulty: Intermediate | Prerequisites: Expression evaluation, loops, basic array syntax
Arrays, ArrayLists, and Scanner-based input processing make up the practical core of CS312. These are the tools you use to store, transform, and read data in Java. Exam questions in this area ask you to write methods from scratch, not just read them, so understanding the patterns deeply matters more than memorising syntax.
This material builds on loop tracing and expression evaluation. If you are not yet comfortable stepping through a for-loop by hand and predicting its output, work through the Expression Evaluation and Code Tracing study notes first. The 2D array and minimum-distance problems add another layer of nested loops on top of the same fundamentals.
Array manipulation problems ask you to create new arrays by copying elements selectively (e.g. excluding a range). ArrayList problems involve removing elements while iterating, which requires backward traversal to avoid skipping. Scanner processing reads tokens one at a time, counts character occurrences, and validates thresholds. 2D array problems apply the same loop logic but with nested row/column iteration and bounds checking.
Array
A fixed-size, ordered collection of elements of the same type. Declared as int[] arr = new int[5]; or int[] arr = {1, 2, 3};. Once created, an array's length cannot change. Think of it as a row of numbered boxes.
ArrayList
A resizable list from java.util. Declared as ArrayList. Unlike arrays, an ArrayList can grow and shrink. Elements are accessed with .get(index), added with .add(value), and removed with .remove(index).
Scanner
A class for reading input from various sources (keyboard, file, String). sc.hasNext() checks whether more tokens exist. sc.next() reads the next whitespace-delimited token as a String. sc.nextInt() reads the next token as an int.
2D array
An array of arrays. Declared as int[][] grid = new int[rows][cols];. Accessed as grid[row][col]. Think of it as a table with rows and columns.
Bounds checking
Ensuring that an index falls within the valid range (0 to length - 1) before accessing an array element. Failing to do this causes ArrayIndexOutOfBoundsException.
copyWithoutRange
A pattern where you create a new array that contains all elements of the original except those in a specified range [start, stop). The new array's size is original.length - (stop - start).
Backward traversal
Iterating from the end of a list to the beginning (for (int i = list.size() - 1; i >= 0; i--)). Required when removing elements from an ArrayList during iteration to avoid skipping elements.
Minimum distance (closest pair)
Finding the two points in a collection with the smallest Euclidean distance between them. Uses nested loops where the inner loop starts at i + 1 to avoid redundant comparisons.
This is a common exam pattern. You are given an array and two indices (start, stop) and must return a new array with those elements removed.
Calculate the new size: vals.length - (stop - start).
Create a new array of that size.
Copy elements before start into the new array.
Skip indices from start to stop - 1.
Copy elements from stop onward into the new array, continuing from where you left off.
The original array must remain unchanged.
Example: copyWithoutRange({0, 1, 2, 3, 4, 5}, 2, 4) produces {0, 1, 4, 5}. Elements at indices 2 and 3 are excluded.
These problems ask you to modify a rectangular subregion of a 2D array, typically clamping values below a threshold.
Determine the starting row and column from the specified corner (often the lower-right corner, working backward).
Ensure your loop bounds do not exceed the array dimensions. Use Math.max(0, startRow) and Math.min(grid.length, endRow) or equivalent guards.
Loop over the rows and columns within the region.
Apply the update condition: if the element is less than the target value, set it to the target.
Ignore cells that fall outside the array.
Example: setting all values below 10 in a specified rectangle to 10.
Array manipulation with bounds checking is the same logic behind image processing (cropping, filtering regions of pixels) and spreadsheet operations (applying a formula to a selected range of cells).
When you remove elements from an ArrayList while iterating, you must iterate backward. If you iterate forward and remove element at index i, all elements after it shift left, so the element that was at i + 1 is now at i, and your loop skips it.
Use for (int i = list.size() - 1; i >= 0; i--) to iterate backward.
Use String.equals() to compare String content (not ==, which compares references).
To remove only the first occurrence of a match per input token, break out of the inner loop after the first removal.
Track the total number of removals with a counter variable.
A common pattern: read all tokens from a Scanner, inspect each character, and count occurrences.
Outer loop: while (sc.hasNext()) processes tokens one at a time.
Inner loop: iterate through each character of the token using token.charAt(i).
Check whether the character falls in a target range (e.g. uppercase letters: ch >= 'A' && ch <= 'Z').
Map each character to an array index: ch - 'A' gives 0 for 'A', 1 for 'B', and so on.
Decrement a required-count array at that index. After all tokens are processed, verify all counts are zero or below to confirm the input met the requirements.
Given an array of Point objects, find the closest pair.
Initialise min with the distance between the first two points: points[0].distance(points[1]).
Use nested loops: outer loop i from 0 to length - 2, inner loop j from i + 1 to length - 1. This ensures each pair is compared exactly once.
If points[i].distance(points[j]) < min, update min.
Return min after all comparisons.
Constraints: use only getX(), getY(), and distance() methods. No additional data structures.
Example: among points (1, 3) and (2, 4), the distance is approximately 1.414 (the square root of 2).
Students often iterate forward through an ArrayList while removing elements, then wonder why some elements get skipped. When you remove index i, everything shifts left. If you do not decrement i or iterate backward, you miss the element that slid into position i.
Students often compare Strings with == instead of .equals(). In Java, == checks whether two references point to the same object in memory, not whether the text is the same. Always use .equals() for String content comparison.
Students often forget that copyWithoutRange should return a new array, not modify the original. The original array must remain unchanged.
Students often mix up row and column indices in 2D arrays. grid[r][c] means row r, column c. Getting them backward leads to ArrayIndexOutOfBoundsException or silently wrong results.
⚠️ Array manipulation (copyWithoutRange-style) is a frequent implementation question. You will be asked to write the method, not just trace it. Practice writing the index management from scratch.
⚠️ ArrayList removal questions test whether you understand the backward-traversal pattern. If your code iterates forward, it is wrong.
⚠️ Scanner + character counting questions combine several skills: loop control, character arithmetic (ch - 'A'), and validation. These often appear as multi-part problems.
⚠️ 2D array questions test bounds checking. The examiners like to give regions that partially fall outside the array to see whether your code handles it without crashing.
⚠️ Minimum distance is a nested-loop pattern. The key detail is starting the inner loop at i + 1 to avoid comparing a point with itself or repeating pairs.
Fill in the blank: when removing from an ArrayList during iteration, you should iterate ____. (Backward.)
True or false: copyWithoutRange({10, 20, 30, 40}, 1, 3) returns {10, 40}. (True.)
Fill in the blank: 'C' - 'A' evaluates to ____. (2)
True or false: in a 2D array, grid[2][3] accesses row 3, column 2. (False. It accesses row 2, column 3.)
True or false: to compare Strings in Java, you should use ==. (False. Use .equals().)
Q: Write the logic for copyWithoutRange(int[] vals, int start, int stop) that returns a new array with elements at indices start through stop - 1 removed.
A: Create a new array of size vals.length - (stop - start). Use a result index variable starting at 0. First loop copies elements from index 0 to start - 1. Second loop copies elements from stop to vals.length - 1. Return the new array. The original array is not modified.
Q: Why must you iterate backward when removing elements from an ArrayList?
A: Because removing an element shifts all later elements left by one. If you iterate forward and remove at index i, the element that was at i + 1 slides to i, and your next iteration goes to i + 1, skipping it. Backward iteration avoids this because the shift only affects indices after the current position, which you have already visited.
Q: Given a 2D array with 3 rows and 4 columns, what happens if you access grid[3][0]?
A: RUNTIME ERROR. ArrayIndexOutOfBoundsException. Valid row indices are 0, 1, and 2. Row 3 does not exist.
Q: How does the character-to-index mapping ch - 'A' work?
A: Characters are stored as numeric values. 'A' is 65, 'B' is 66, and so on. Subtracting 'A' from any uppercase letter gives its position in the alphabet starting from 0. So 'C' - 'A' = 67 - 65 = 2. This lets you use a 26-element array to count occurrences of each letter.
Q: In the minimum distance problem, why does the inner loop start at j = i + 1 instead of j = 0?
A: Starting at i + 1 prevents comparing a point with itself (which would always give distance 0) and avoids checking the same pair twice (since distance(A, B) equals distance(B, A)). This cuts the number of comparisons roughly in half.
Array and ArrayList manipulation builds directly on the loop tracing and expression evaluation skills covered in the Expression Evaluation study notes. If you can trace a for-loop over a 1D array, extending that to nested loops over a 2D array is the same skill applied twice.
The Critter class design (covered in the OOP study notes) often uses arrays or step counters internally. The character-counting pattern with Scanner is also useful preparation for file I/O topics later in the course, where you process larger inputs line by line.
Java array manipulation CS312, copyWithoutRange, array range removal, ArrayList remove while iterating, backward traversal ArrayList, Scanner hasNext next, character counting Java, ch minus A mapping, 2D array bounds checking, clamping values 2D array, minimum distance closest pair points, nested loops Java, ArrayIndexOutOfBoundsException, String.equals vs ==, UT Austin CS312 arrays