Unit 4 Practice Exam: Arrays and ArrayLists
Fundamental Array Declarations and Initialization
Arrays in Java are objects that store multiple values of the same type in a contiguous memory location.
The length of an array is fixed upon creation and can be determined by different initialization methods:
int[] nums = new int[5];creates an array of integers with a length of . All elements are initialized to the default value for integers, which is .int[] nums = {2,4,6,8,10};creates an array with specific values. The length is determined by the number of elements provided in the curly braces. In this instance, the length is .int[] nums = new int[]{7,8,9,10};is an anonymous array initialization. The length is determined by the count of elements in the braces, which is .
Valid and Invalid Array Declarations:
- Valid:
String[] colors = {"Red","Blue","Green"};correctly storesStringliterals in aStringarray. - Invalid:
String[] values = {1,2,3};will result in a compiler error because integer literals cannot be stored directly into aStringarray. - Valid:
double[] grades = {88.5,91.2,77.8};correctly storesdoubleliterals in adoublearray.
- Valid:
1D Array Traversal and Element Manipulation
Traversing an array typically involves a
forloop that iterates from index tolength - 1.- Example:
String[] letters = {"J","A","V","A"}; - When iterated with
for(int i=0; i<letters.length; i++) { System.out.print(letters[i]); }, the output isJAVAbecause it prints every element at each index from to .
- Example:
Calculations with Array Indices:
- Given
int[] values = {10,20,30,40,50};, - The expression
values[(values.length-1)]-20is evaluated by first finding the index:values.lengthis , sovalues.length - 1is . values[4]is the fifth element, which is .- The final calculation is .
- Given
Selective Element Modification:
- Modification logic often uses the loop increment to target specific elements.
- Given
int[] arr = {2,4,6,8,10,12};and the loopfor(int i=0;i<arr.length;i+=2) { arr[i]+=3; }: - When
i = 0:arr[0]becomes . - When
i = 2:arr[2]becomes . - When
i = 4:arr[4]becomes . - The values at odd indices () remain unchanged. The resulting array is
{5, 4, 9, 8, 13, 12}.
String Processing and Searching Within Arrays
Counting specific elements requires a counter variable and a conditional check.
- Correct approach for counting names containing "Smith":
int count=0; for(int i=0;i<names.length;i++) { if(names[i].contains("Smith")) count++; }.
Aggregating String Lengths:
- For an array
String[] words={"Cat","Elephant","Dog"};, - Iterating and summing
.length()calls returns the total character count. "Cat"has length ,"Elephant"has length , and"Dog"has length .- Total: .
- For an array
Patterns with Modulo Operators:
- Using
i % 2 == 0allows for alternating values in an array. - For
String[] gameBoard = new String[6];, - If
i % 2 == 0,gameBoard[i] = "A". (Indices ). - Else,
gameBoard[i] = "B". (Indices ). - Resulting array:
["A","B","A","B","A","B"].
- Using
Multidimensional (2D) Array Structure
Initialization Syntax:
- Correct initialization of a 2D array with specific values:
int[][] nums={ {1,2,3}, {4,5,6} };. This creates rows and columns. - Creating an empty grid:
int[][] board = new int[5][8];creates a grid with rows and columns. - For
doubletypes:double[][] scores = new double[4][3];creates rows and columns.
- Correct initialization of a 2D array with specific values:
2D Array Sizing Properties:
- For a 2D array named
data: data.lengthreturns the number of rows.data[0].lengthreturns the number of columns in the first row.- Given
double[][] data= { {1.5,2.5,3.5}, {4.5,5.5,6.5}, {7.5,8.5,9.5} };: data.lengthis .data[0].lengthis .
- For a 2D array named
Accessing 2D Array Elements:
- Elements are accessed via
array[row][column](0-indexed). data[1][2]refers to the element in the second row, third column, which is .data[2][1]refers to the element in the third row, second column, which is .
- Elements are accessed via
Modifying 2D Array Content:
- To replace a single value:
data[2][1] = 10.0;updates the value previously known as . - To replace an entire row: Since a 2D array is an array of arrays,
data[1]refers to the second row. You can assign a new 1D array to it:double[] temp = {10,20,30}; data[1] = temp;.
- To replace a single value:
Nesting Loops for 2D Traversal:
- To visit every element, nested
forloops are used: for(int r=0; r<array.length; r++) { for(int c=0; c<array[r].length; c++) { ... } }.
- To visit every element, nested
The ArrayList Class and Dynamic Collections
Size and Access Methods:
- Unlike standard arrays,
ArrayListuses the.size()method to determine how many elements it contains. - Accessing elements requires the
.get(index)method. Using bracket syntax likelist[i]on anArrayListcauses a compiler error.
- Unlike standard arrays,
Type Restrictions (Generics):
ArrayListcan only store objects, not primitive types.ArrayList<double> nums = new ArrayList<double>();is invalid. It must use the wrapper classDouble:ArrayList<Double> nums = new ArrayList<Double>();.
ArrayList Traversal Logic:
- Given
ArrayList<Integer> numscontaining{1, 2, 3, 4}: - If traversing with
for(int i=1; i<nums.size(); i+=2): i = 1:total += nums.get(1)(value is ).i = 3:total += nums.get(3)(value is ).- Total: .
- Given
Dynamic Sizing and Removal:
- When an element is removed using
.remove(index), all subsequent elements shift to the left to fill the gap. - Given
words = ["I", "love", "Java", "class"]: words.remove(1);removes"love".- The list shifts to
["I", "Java", "class"]. words.get(1)now returns"Java"because it shifted from index to index .
- When an element is removed using