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 55. All elements are initialized to the default value for integers, which is 00.
    • 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 55.
    • 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 44.
  • Valid and Invalid Array Declarations:

    • Valid: String[] colors = {"Red","Blue","Green"}; correctly stores String literals in a String array.
    • Invalid: String[] values = {1,2,3}; will result in a compiler error because integer literals cannot be stored directly into a String array.
    • Valid: double[] grades = {88.5,91.2,77.8}; correctly stores double literals in a double array.

1D Array Traversal and Element Manipulation

  • Traversing an array typically involves a for loop that iterates from index 00 to length - 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 is JAVA because it prints every element at each index from 00 to 33.
  • Calculations with Array Indices:

    • Given int[] values = {10,20,30,40,50};,
    • The expression values[(values.length-1)]-20 is evaluated by first finding the index: values.length is 55, so values.length - 1 is 44.
    • values[4] is the fifth element, which is 5050.
    • The final calculation is 5020=3050 - 20 = 30.
  • 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 loop for(int i=0;i<arr.length;i+=2) { arr[i]+=3; }:
    • When i = 0: arr[0] becomes 2+3=52 + 3 = 5.
    • When i = 2: arr[2] becomes 6+3=96 + 3 = 9.
    • When i = 4: arr[4] becomes 10+3=1310 + 3 = 13.
    • The values at odd indices (1,3,51, 3, 5) 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 33, "Elephant" has length 88, and "Dog" has length 33.
    • Total: 3+8+3=143 + 8 + 3 = 14.
  • Patterns with Modulo Operators:

    • Using i % 2 == 0 allows for alternating values in an array.
    • For String[] gameBoard = new String[6];,
    • If i % 2 == 0, gameBoard[i] = "A". (Indices 0,2,40, 2, 4).
    • Else, gameBoard[i] = "B". (Indices 1,3,51, 3, 5).
    • Resulting array: ["A","B","A","B","A","B"].

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 22 rows and 33 columns.
    • Creating an empty grid: int[][] board = new int[5][8]; creates a grid with 55 rows and 88 columns.
    • For double types: double[][] scores = new double[4][3]; creates 44 rows and 33 columns.
  • 2D Array Sizing Properties:

    • For a 2D array named data:
    • data.length returns the number of rows.
    • data[0].length returns 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.length is 33.
    • data[0].length is 33.
  • 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 6.56.5.
    • data[2][1] refers to the element in the third row, second column, which is 8.58.5.
  • Modifying 2D Array Content:

    • To replace a single value: data[2][1] = 10.0; updates the value previously known as 8.58.5.
    • 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;.
  • Nesting Loops for 2D Traversal:

    • To visit every element, nested for loops are used:
    • for(int r=0; r<array.length; r++) { for(int c=0; c<array[r].length; c++) { ... } }.

The ArrayList Class and Dynamic Collections

  • Size and Access Methods:

    • Unlike standard arrays, ArrayList uses the .size() method to determine how many elements it contains.
    • Accessing elements requires the .get(index) method. Using bracket syntax like list[i] on an ArrayList causes a compiler error.
  • Type Restrictions (Generics):

    • ArrayList can only store objects, not primitive types.
    • ArrayList<double> nums = new ArrayList<double>(); is invalid. It must use the wrapper class Double: ArrayList<Double> nums = new ArrayList<Double>();.
  • ArrayList Traversal Logic:

    • Given ArrayList<Integer> nums containing {1, 2, 3, 4}:
    • If traversing with for(int i=1; i<nums.size(); i+=2):
    • i = 1: total += nums.get(1) (value is 22).
    • i = 3: total += nums.get(3) (value is 44).
    • Total: 2+4=62 + 4 = 6.
  • 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 22 to index 11.