Arrays, ArrayLists, and 2D Arrays, CS312 – Study Notes
offline

Overview

Date: CS312 Credit by Exam, Sample 2 | Source: University of Texas at Austin, Introduction to Computer Programming

Tags: arrays, 2D arrays, ArrayList, array reversal, subarray, insert at front, element shifting, ArrayList removal, back-to-front traversal, charAt, String searching, greedy algorithm, matrix traversal, bounds checking, off-by-one error

Difficulty: Intermediate to Advanced. Prerequisites: loops, methods, basic array syntax, and understanding of reference types.

Arrays, ArrayLists, and 2D arrays make up the bulk of the programming questions on the CS312 exam, collectively worth 62 points across four questions. These problems test whether you can manipulate data structures in place, avoid off-by-one errors, handle edge cases (like arrays of different lengths), and traverse a matrix with constraints. If you can write a correct loop with the right bounds and index arithmetic, you can handle nearly every array question the exam throws at you.


TL;DR

Array questions test three core skills: creating a new array of the right size, looping with correct bounds, and placing values at the right indices. ArrayList questions add the complication of removing elements while iterating (traverse back to front to avoid skipping). 2D array questions combine traversal with decision-making, often requiring bounds checking to avoid ArrayIndexOutOfBoundsException.


Key Terms

Array

A fixed-size, ordered collection of elements, all of the same type, accessed by integer index starting at 0. Once created, its length cannot change.

In simple terms, a numbered row of boxes that holds values. You pick the size when you create it, and that is final.

ArrayList

A resizable list from java.util that grows and shrinks as elements are added or removed. Elements are accessed with .get(index), not square brackets. Removal shifts all subsequent elements down.

Think of it as: an array that can change size, but you must use method calls (.get(), .add(), .remove(), .size()) instead of bracket notation.

2D array (matrix)

An array of arrays. Accessed with two indices: mat[row][col]. The number of rows is mat.length. The number of columns is mat[0].length (assuming all rows are the same length).

In simple terms, a grid of values, like a spreadsheet. The first index picks the row, the second picks the column.

Off-by-one error (OBOE)

A bug where a loop runs one iteration too many or too few, or an index is one position off. The most common source of errors in array problems. The exam deducts 2 points for OBOE.

Think of it as: the fencepost problem. If you have 10 fence sections, you need 11 posts.

Bounds checking

Verifying that an index is within the valid range before using it. For an array of length n, valid indices are 0 through n-1. Accessing mat[row-1][col] without first checking row > 0 will crash if row is 0.

In simple terms, always check that you are not about to walk off the edge of the array.

Reference parameter (for arrays)

When an array is passed to a method, the method receives a reference to the same array, not a copy. Changes to the array's contents inside the method are visible outside. However, reassigning the parameter variable itself (e.g. one = new int[5]) does not affect the original.

Think of it as: the method gets a map to the same house, not a copy of the house. It can rearrange the furniture, but if it draws a new map, the original map still points to the old house.

Back-to-front traversal

Iterating through a list from the last element to the first, used when removing elements from an ArrayList. If you remove while traversing forward, you skip the element that shifts into the removed position.

In simple terms, when removing items from a list, start at the end so your removals do not mess up the indices you have not visited yet.


Core Content

Reversing a Subarray (12 points)

The getReversedSubList method takes an array, a startIndex, and a stopIndex, and returns a new array containing the elements from startIndex to stopIndex-1, in reverse order.

  • Create the result array with the correct size: new int[stopIndex - startIndex]

  • Use a counter (indexVals) starting at stopIndex - 1 and decrementing, or calculate the source index as stopIndex - i - 1

  • Copy into result[i] from vals[indexVals]

  • Return the result array

  • Do not alter the original array. Modifying the parameter costs 4 points

Inserting Elements at the Front of an Array (16 points)

The insertElementsAtFront method takes two arrays and places the second array's elements at the front of the first, shifting existing elements to make room.

  • First, shift existing elements in the first array to the right to make room:

    • Calculate how many elements to move: numMove = one.length - two.length

    • Shift from back to front (i = numMove - 1 down to 0) to avoid overwriting: one[i + two.length] = one[i]

    • Shifting must go right to left. Left to right would overwrite elements before they are moved

  • Then, determine how many elements from the second array to copy:

    • If two.length > one.length, you can only copy one.length elements

    • limit = Math.min(one.length, two.length)

  • Copy: for (int i = 0; i < limit; i++) { one[i] = two[i]; }

  • This method returns void. It modifies the first array in place

  • Creating a new array costs 4 points. Using nested loops costs 4 points

  • Reassigning the parameter (one = temp) does not work because array parameters are references. The original variable outside the method still points to the old array. This costs 3 points

ArrayList Removal with String Searching (16 points)

The removeValues method takes an ArrayList of Strings, a char, and an int n. It removes every String that contains the char within its first n characters, and returns the count of removals.

  • Traverse the ArrayList from back to front: for (int i = list.size() - 1; i >= 0; i--)

    • Back-to-front traversal is worth 5 points. Forward traversal while removing skips elements

  • For each String, search its first n characters for the target char:

    • Use a while loop with three conditions: index < n, index < s.length(), and !found

    • Check s.charAt(index) == c

    • Stop as soon as the char is found (no need to keep searching)

  • If found, call list.remove(i) and increment the counter

  • Use .get(index), not list[index]. Treating ArrayList like an array costs 4 points

  • Return the total number of elements removed

2D Array Traversal: Coin Collection (18 points)

The coinsCollected method simulates a robot moving through a grid, collecting coins. The robot starts at a given row in column 0 and moves toward the last column, choosing the adjacent cell (up, down, or right) with the most coins.

  • Track the current row and column. Start at (initialRow, 0)

  • Loop while the column is less than mat[0].length - 1 (not yet at the last column)

  • At each step:

    • Add mat[row][col] to the total

    • Mark the current cell as visited by setting it to -1 (prevents the robot from circling back)

    • Check three neighbours: up (row-1, col), down (row+1, col), and right (row, col+1)

    • For up and down, bounds-check first (row > 0 for up, row + 1 < mat.length for down). Set the value to -1 if out of bounds

    • Move in the direction with the highest value. Ties are broken: up wins over down, up wins over right, down wins over right

  • After the loop, add the last cell's value (mat[row][col]) to the total

  • Return the total

  • Marking visited cells is worth 5 points. Without it, the robot can loop forever

  • An infinite loop due to logic error costs 6 points


Common Misconceptions

  • Students often shift array elements left to right when making room at the front. This overwrites values before they are moved. You must shift from right to left (high index to low index).

  • Students often remove elements from an ArrayList while traversing forward. This skips the element that shifts into the removed slot. Traverse back to front instead, or use an iterator.

  • Students often use list[i] syntax on an ArrayList. ArrayLists require method calls: list.get(i), list.remove(i), list.size(). Square bracket access is for arrays only.

  • Students often reassign an array parameter inside a method and expect the caller to see the new array. Because Java passes references by value, reassigning the local variable does not affect the caller. You must modify the existing array's contents in place.

  • Students often forget to bounds-check when accessing neighbours in a 2D array. Checking mat[row-1][col] when row is 0, or mat[row+1][col] when row is the last row, throws ArrayIndexOutOfBoundsException.

  • Students often create new Strings (using substring or concatenation) instead of using charAt() to check individual characters. Creating new Strings costs 4 points on the ArrayList question.


Why It Matters / Exam Flags

  • The four array/ArrayList/2D array questions together are worth 62 points out of the total exam. This is the highest-value section by far.

  • Off-by-one errors (OBOE) cost 2 points each. Double-check your loop bounds before moving on.

  • Back-to-front ArrayList traversal during removal is worth 5 points on its own. This is a pattern to memorise.

  • Creating a new array when the method should modify in place costs 4 points. Read the return type: void means in-place modification.

  • The 2D array question awards 5 points for marking visited cells. Without that logic, your robot can revisit cells and loop forever.

  • Partial credit is available for most questions. Even if your loop bounds are slightly wrong, getting the structure right earns significant marks.

  • The grading accepts multiple correct approaches. For the subarray reversal, you can use a decrementing counter or calculate the index with arithmetic. Both are full marks.


Quick Self-Test

  1. True or false: When removing elements from an ArrayList in a loop, you should traverse from index 0 forward. (Answer: False. Traverse from the last index backward to avoid skipping elements.)

  1. Fill in the blank: To access element i of an ArrayList called items, write items.______. (Answer: get(i))

  1. True or false: If a method receives an int[] parameter and reassigns it (arr = new int[10]), the caller's array changes. (Answer: False. Java passes references by value. Reassigning the local variable does not affect the caller.)

  1. Fill in the blank: The number of rows in a 2D array mat is mat., and the number of columns is mat[0].. (Answer: length, length)

  1. True or false: When shifting array elements to the right, you should start shifting from the leftmost element. (Answer: False. Start from the rightmost element to avoid overwriting values.)


Practice Q&A

Q: Given int[] vals = {10, 20, 30, 40, 50}, what does getReversedSubList(vals, 1, 4) return?

A: {40, 30, 20}. The subarray from index 1 to 3 (inclusive) is {20, 30, 40}. Reversed, that is {40, 30, 20}.

Q: Why must you shift elements from right to left when inserting at the front of an array?

A: If you shift left to right, each element overwrites the one to its right before that one has been moved. Starting from the rightmost element ensures each value is safely relocated before its slot is reused.

Q: You need to remove all Strings from an ArrayList that start with the letter 'A'. Write the loop header.

A: for (int i = list.size() - 1; i >= 0; i--). Back-to-front traversal prevents skipping elements after a removal.

Q: In a 2D array, how do you check whether moving up is valid before accessing mat[row-1][col]?

A: Check if (row > 0) before accessing mat[row-1][col]. If row is 0, there is no row above, and the access would throw ArrayIndexOutOfBoundsException.

Q: A method receives an int[] and is supposed to modify its contents. It creates a new local array, fills it, and then sets the parameter equal to it. Why does this not work?

A: Java passes array references by value. The parameter is a copy of the reference. Reassigning the copy (parameter = newArray) does not change the original reference in the caller. To modify the original array, you must change its elements in place using indexed assignment.

Q: What is the purpose of setting mat[row][col] = -1 in the coin collection problem?

A: It marks the cell as visited so the robot does not circle back to it. Without this, the robot could move up, then back down to the same cell, creating an infinite loop.


Connections to Other Topics

Array manipulation connects to every other topic in CS312. Expression evaluation determines your index arithmetic. OOP concepts (reference types, parameter passing) explain why arrays behave differently from primitives when passed to methods. The 2D array greedy traversal is a simplified version of dynamic programming problems you will see in later courses (CS314). ArrayList removal connects to the Iterator pattern, which you will encounter in data structures.


Related Terms / Search Tags

Java arrays, int array, array reversal, subarray extraction, reversed subarray, array shifting, insert at front array, in-place array modification, ArrayList removal, ArrayList remove while iterating, back-to-front loop, backwards traversal, ArrayList .get(), ArrayList .remove(), ArrayList .size(), 2D array Java, matrix traversal, greedy algorithm grid, bounds checking array, ArrayIndexOutOfBoundsException, off-by-one error OBOE, reference parameter Java, pass by value, charAt String searching, CS312 credit by exam