← Unit 6: Arrays
ICS3U · Unit 6 test review
Arrays: Test Review
Everything for the Unit 6 test on one page: the key facts from all 5 lessons, the mistakes that cost the most marks, and a practice test that points you back to the lessons you need.
Key facts
Declaring and Using Arrays
int[] a = new int[n];creates n slots filled with the default value;int[] a = {1, 2, 3};creates and fills in one step.- Indexes start at 0, so the valid range is 0 to and the last element is
a[a.length - 1]. - Arrays use
.lengthwith no brackets; Strings use.length()with brackets. - Defaults: 0 for whole numbers, 0.0 for decimals, false for boolean, null for String and other objects.
- An array's length is fixed at creation and can never change.
- Any index below 0 or at least equal to the length throws ArrayIndexOutOfBoundsException.
Traversing Arrays and the Standard Algorithms
- The standard traversal is
for (int i = 0; i < arr.length; i++)— strict less-than, never<=. - Use for-each when you need only the values; use the index loop when you must modify elements or report a position.
- Assigning to a for-each loop variable changes a copy and leaves the array unchanged.
- Initialize a max or min search with
arr[0], never with 0, then loop from index 1. - A linear search returns the index on a match and −1 after the loop if nothing matched.
- Swapping needs a temporary variable, and reversing swaps from both ends inwards for
length / 2passes.
Sorting and Binary Search
- Selection sort: each pass finds the smallest unsorted value and swaps it into the next slot; n elements need n − 1 passes and n(n − 1)/2 comparisons.
- Bubble sort: each pass swaps out-of-order neighbours, carrying the largest remaining value to the end; a pass with no swaps means the array is sorted.
- Swapping two elements always needs a temporary variable: save, copy over, restore.
- Java passes arguments by value, but an array variable's value is a reference, so a method can change the caller's elements — not which array the caller's variable points to.
- Binary search requires sorted data; it checks the middle, then discards half the range, using
low = mid + 1orhigh = mid - 1. - Worst-case binary search on n elements needs floor(log₂ n) + 1 checks — 20 for a million elements, against a million for linear search.
Strings as Sequences of Characters
- String characters are indexed from 0 to
s.length() - 1;length()is a method with brackets, unlike an array'slengthfield. s.charAt(i)returns achar;s.substring(a, b)returns the characters from index a up to but not including b, so its length is b − a.s.indexOf(x)returns the index of the first occurrence of x, or −1 if it is absent.- Strings are immutable:
toUpperCase,toLowerCaseandsubstringreturn new Strings, so store the result. - Use
equalsorequalsIgnoreCasefor matching text, andcompareTofor order: negative means first, 0 means equal, positive means after. - A position outside 0 to length − 1 throws StringIndexOutOfBoundsException.
Two-Dimensional Arrays
int[][] grid = new int[3][4];makes 3 rows of 4 columns — 12 cells, all starting at 0.- A cell is
grid[row][col]: row first, column second, both counting from 0. grid.lengthis the number of rows;grid[0].lengthis the number of columns.- Nested loops traverse a grid — outer loop over rows, inner loop over columns.
- The inner body runs rows times columns times in total, so a 3 by 4 grid means 12 passes.
- Java stores grids in row-major order: all of row 0, then all of row 1, and so on.
Where marks get lost
- Treating the first element as index 1.
a[1]is the second element, so every value comes out shifted by one. (Declaring and Using Arrays) - Writing
a.length()for an array ors.lengthfor a String — the presence or absence of brackets is not optional. (Declaring and Using Arrays) - Looping with
i <= a.length, which runs one pass too many and throws on the last one. (Declaring and Using Arrays) - Expecting a
String[]to start full of empty strings. It starts full of null, so calling a method on an unassigned element throws a NullPointerException. (Declaring and Using Arrays) - Trying to grow an array by assigning past the end. The length is fixed; you must build a bigger array and copy. (Declaring and Using Arrays)
- Using
i <= arr.lengthin the loop condition, which throws ArrayIndexOutOfBoundsException on the final pass. (Traversing Arrays and the Standard Algorithms) - Trying to modify elements inside a for-each loop — the loop variable is a copy, so the array never changes. (Traversing Arrays and the Standard Algorithms)
- Starting a maximum search at 0 instead of
arr[0], which reports 0 for all-negative data. (Traversing Arrays and the Standard Algorithms) - Putting
return -1;inside the search loop, so failure is declared after checking only the first element. (Traversing Arrays and the Standard Algorithms) - Sorting or editing one parallel array and not the others, silently pairing every name with the wrong data. (Traversing Arrays and the Standard Algorithms)
- Swapping inside selection sort's inner loop every time a smaller value is found, instead of remembering
minIndexand swapping once after the scan. (Sorting and Binary Search) - Writing the inner bubble-sort loop as
j < arr.length, soarr[j + 1]runs one past the end and throws ArrayIndexOutOfBoundsException. (Sorting and Binary Search) - Running binary search on an unsorted array and trusting the −1 it returns. (Sorting and Binary Search)
- Writing
low = midorhigh = midinstead ofmid + 1andmid - 1, which can loop forever once low and high are next to each other. (Sorting and Binary Search) - Expecting a method that assigns
arr = new int[...]to replace the caller's array — it only redirects the method's own copy of the reference. (Sorting and Binary Search) - Using
s.length(no brackets) on a String orarr.length()on an array — each is a compile error. (Strings as Sequences of Characters) - Expecting
substring(1, 4)to include index 4. The end index is excluded, so it returns three characters. (Strings as Sequences of Characters) - Calling
name.toUpperCase();without storing the result, then wondering whynameis unchanged. (Strings as Sequences of Characters) - Comparing whole Strings with
==instead ofequals, which can pass in testing and fail on typed input. (Strings as Sequences of Characters) - Looping with
i <= s.length()or callings.charAt(s.length()), which throws StringIndexOutOfBoundsException. (Strings as Sequences of Characters) - Writing
grid[col][row]instead ofgrid[row][col]— on a square grid this reads the wrong cell with no error at all. (Two-Dimensional Arrays) - Using
grid.lengthwhen you meant the number of columns. Columns come fromgrid[0].length. (Two-Dimensional Arrays) - Putting the bare
System.out.println()inside the inner loop, so every value prints on its own line. (Two-Dimensional Arrays) - Declaring a per-row total outside the outer loop, so each line reports a running grand total instead. (Two-Dimensional Arrays)
- Forgetting that a
String[][]starts full of null, then calling a method on an unassigned cell and getting a NullPointerException. (Two-Dimensional Arrays)
Practice test
25 questions from across the unit. Each one shows the lesson it comes from.
- Declaring and Using Arrays1For
int[] a = {5, 10, 15, 20};, what is the value ofa[1]? - Declaring and Using Arrays2After
int[] a = new int[4];anda[2] = 7;, what doesa[0] + a[2]evaluate to? - Declaring and Using Arrays3Why does
arr[arr.length]throw for every array, no matter its size? - Declaring and Using Arrays4How many elements does
int[] grid = new int[12];hold? - Declaring and Using Arrays5What is the main cost of an array's fixed size?
- Traversing Arrays and the Standard Algorithms6What is printed?
int[] a = {4, 7, 2, 9}; int t = 0; for (int v : a) { t += v; } System.out.println(t); - Traversing Arrays and the Standard Algorithms7By convention, what value does a linear search return when the target is not in the array?
- Traversing Arrays and the Standard Algorithms8Order the three statements that correctly swap
a[i]anda[j].- 1
a[i] = a[j]; - 2
int temp = a[i]; - 3
a[j] = temp;
- 1
- Traversing Arrays and the Standard Algorithms9Why does a reverse loop use the condition
i < a.length / 2? - Traversing Arrays and the Standard Algorithms10
int[] a = {5, 10}; double avg = a[0] + a[1] / 2;gives 10.0 instead of 7.5. What is wrong? - Sorting and Binary Search11Selection sort is applied to
{29, 10, 14, 37, 13, 5}. What is the array after the FIRST pass? - Sorting and Binary Search12
int[] d = {3, 8, 12, 17, 21, 26, 30, 34, 41, 45, 52, 58, 63, 70, 77};What doesbinarySearch(d, 58)return? - Sorting and Binary Search13
binarySearch(d, 21)runs on{3, 8, 12, 17, 21, 26, 30, 34, 41, 45, 52, 58, 63, 70, 77}. Put the elements it checks in the order it checks them.- 1d[3] = 17
- 2d[4] = 21
- 3d[5] = 26
- 4d[7] = 34
- Sorting and Binary Search14Match each algorithm to its defining action.Selection sortBubble sortLinear searchBinary search
- Sorting and Binary Search15Binary search is run on
{3, 8, 12, 17, 21, 26, 30, 34, 41, 45, 52, 58, 63, 70, 77}for the target 40. How many times does the body of the while loop run?passes - Strings as Sequences of Characters16What does
"Mississauga".length()return? - Strings as Sequences of Characters17What does
"Mississauga".indexOf("ss")return? - Strings as Sequences of Characters18What is the sign of
"cat".compareTo("car")? - Strings as Sequences of Characters19Put these Strings in the order
compareTosorts them, smallest first.- 1"apple"
- 2"banana"
- 3"apples"
- 4"Zebra"
- Strings as Sequences of Characters20
String w = "hello"; System.out.println(w.charAt(w.length()));What happens? - Two-Dimensional Arrays21For
int[][] g = new int[6][4];what doesg.lengthreturn? - Two-Dimensional Arrays22In
seats[2][5], what do the two numbers mean? - Two-Dimensional Arrays23For
int[][] t = {{1, 2, 3}, {4, 5, 6}};what is the total of column 2? - Two-Dimensional Arrays24Match each expression to what it refers to for
int[][] g = new int[3][5];g.lengthg[0].lengthg[1]g[2][4] - Two-Dimensional Arrays25What does
String[][] board = new String[3][3];contain immediately after creation?
Endless drill
Fresh numbers every time, for the calculation questions in this unit.
Endless drillnew numbers every time
Generating a problem…