Comprehensive Study Guide to Java Arrays: 1D and 2D Implementations

Overview and Core Fundamentals of Java Arrays

  • Curriculum and Scope:

    • Course: CC102 – Computer Programming 1.

    • Module: CC102 - Module 7.

    • Subject Matter: Java Arrays.

    • Instructor / Source Credit: Ms. Gemmarie T. Muñoz.

  • Definition of an Array:

    • An array in Java is a data structure used to store multiple values of the same data type within a single variable, eliminating the need to declare separate variables for each individual value.

    • Rather than creating distinct variables (e.g., score1, score2, score3), an array allows homogeneous data to be grouped under a unified identifier.

  • The Built-in Length Property:

    • Arrays in Java possess a built-in length property that stores the total number of elements an array can hold.

    • The value of length is established when the array is instantiated and provides an easy mechanism to inspect the capacity and boundary of the collection.

Array Elements and Indexing Mechanisms

  • Array Elements:

    • Elements are the individual items or values stored inside an array.

    • Every slot in the array contains exactly one element belonging to the declared data type.

  • Definition and Mechanics of an Index:

    • An index is a numerical value that represents the exact position of an element within the collection.

    • Java employs a zero-based indexing system:

    • The first element is situated at index [0] (position 00).

    • The second element is situated at index [1] (position 11).

    • The nn-th element is located at index [n - 1].

    • The highest valid index in any array is always length−1\text{length} - 1.


Visualization of Array Elements and Zero-Based Indices
  • Concrete Element Mapping Example:

    • Consider an array storing five string names:

    • Index 0: Value "DIANE"

    • Index 1: Value "ARDI"

    • Index 2: Value "JAN"

    • Index 3: Value "MARLYN"

    • Index 4: Value "AEZAY"

    • The total number of elements (length\text{length}) is 55, with valid indices ranging from 00 to 44.

Array Declaration and Initialization Strategies

  • Declaring with Values (Static Initialization):

    • Used when the exact elements and collection size are known at the time of declaration.

    • Syntax:java datatype identifier[] = {value1, value2, value3, value4};     

  • Sample Code:java String names[] = {"Marlyn", "Pio", "Ron", "Angelyn"};     

    • Operational Behavior:

    • This creates an array containing the exact elements specified within the curly braces ({}).

    • The size is implicitly calculated based on the count of provided elements (in this example, a size of 44).

  • Declaring Without Values (Dynamic Initialization):

    • Used when the array capacity is known in advance, but the actual element values will be assigned later during execution.

    • Syntax:java datatype identifier[] = new datatype[size];     

  • Sample Code:java int numbers[] = new int[5];     

    • Operational Behavior:

    • Allocates memory space capable of holding the specified size (in this case, 55 integer elements).

    • Fills all allocated slots with the language's default values for that data type (for numeric types such as int, the default value is 00; for boolean, it is false; for reference types, it is null).

  • Inspecting Array Length:

    • To determine the total number of elements an array is allocated to hold, access the array's length attribute.

    • Syntax and Usage:java System.out.println(names.length);     

  • Note: length is an immutable instance field, not a method, so parentheses are not used.

Accessing and Modifying Array Elements

  • Reading an Array Element:

    • To retrieve or inspect the value stored at a specific position, specify the array's identifier followed by the desired index enclosed in square brackets.

    • Syntax:java identifier[index];     

  • Sample Code:java names[0]; // Retrieves the element at index 0     

  • Modifying an Array Element:

    • Elements are mutable; a new value can be assigned directly to any existing valid index using the assignment operator (=).

    • Syntax:java identifier[index] = new value;     

  • Sample Code:java names[0] = "Cutie";     

  • Effect:

    • The value previously stored at index 0 (e.g., "Marlyn") is overwritten and replaced by "Cutie".

Array Traversal Using For Loops

  • Purpose of the Indexed for Loop:

    • Provides direct programmatic access to both the loop counter (the index) and the corresponding value of each array item.

    • Particularly essential when an operation requires:

    • Knowing the specific numeric position of each element during execution.

    • Comparing adjacent elements side-by-side (such as in sorting or searching algorithms).

    • Modifying element values in place based on position.

  • Complete 1D Array Implementation (Sample.java):

  public class Sample {//class starts here

      public static void main(String[] args) {//main method starts here

          int[] scores = {85, 90, 78, 92, 88};

          for (int i = 0; i < scores.length; i++) {
              System.out.println("scores[" + i + "] = " + scores[i]);
          }

      }//main method ends here
  }//class ends here
&nbsp;&nbsp;```

* **Compilation, Execution, and Terminal Output:**
  * **Compilation command:** `javac Sample.java`
  * **Execution command:** `java Sample`
  * **Console Output:**
    ```text
    scores[0] = 85
    scores[1] = 90
    scores[2] = 78
    scores[3] = 92
    scores[4] = 88
&nbsp;&nbsp;&nbsp;&nbsp;```
* **Iteration Trace:**
  * Iteration 11 (i=0i = 0): outputs index `0`, value `85`.
  * Iteration 22 (i=1i = 1): outputs index `1`, value `90`.
  * Iteration 33 (i=2i = 2): outputs index `2`, value `78`.
  * Iteration 44 (i=3i = 3): outputs index `3`, value `92`.
  * Iteration 55 (i=4i = 4): outputs index `4`, value `88`.
  * When ii increments to 55, the loop condition `i < scores.length` (5<55 < 5) evaluates to `false`, terminating the loop.


# Two-Dimensional (2D) Arrays

* **Conceptual Model:**
  * A two-dimensional array is an array of arrays.
  * Mentally and functionally structured like a table or grid containing rows and columns.
  * Each individual element requires two indices for unambiguous identification: the **row index** and the **column index**.
  * **Common Real-World Applications:**
    * Grids and coordinate planes.
    * Mathematical matrices.
    * Classroom or theater seating charts.
    * Student grade tables.

* **Declaration and Initialization of 2D Arrays:**
  * **Static Initialization:**
    * Nested curly braces define each row of elements explicitly.
    ```java
    int[][] matrix = {
        {1, 2, 3}, // row 0
        {4, 5, 6}, // row 1
        {7, 8, 9}  // row 2
    };
&nbsp;&nbsp;&nbsp;&nbsp;```
* **Dynamic Initialization:**
  * Specifies the dimensions (row size and column size) using `new`.
    ```java
    int[][] grid = new int[3][3]; // 3 rows, 3 columns, initialized to all zeros
&nbsp;&nbsp;&nbsp;&nbsp;```

* **Element Access and Dimensional Properties:**
  * **Syntax:** `identifier[rowIndex][columnIndex]`
  * Accessing row 00, column 00: `matrix[0][0]` yields value `1`.
  * Accessing row 11, column 22: `matrix[1][2]` yields value `6`.
  * Accessing row 22, column 11: `matrix[2][1]` yields value `8`.
  * **Row Count:** `matrix.length` returns the total number of rows (here, 33).
  * **Column Count:** `matrix[0].length` returns the number of columns in row 00 (here, 33).

* **Complete 2D Array Implementation (`Sample.java`):**

java public class Sample {//class starts here public static void main(String[] args) {//main method starts here

      // Static initialization
      int[][] matrix = {
          {1, 2, 3}, // row 0
          {4, 5, 6}, // row 1
          {7, 8, 9}  // row 2
      };

      // Dynamic initialization
      int[][] grid = new int[3][3]; // 3 rows, 3 columns, all zeros

      // Accessing elements
      System.out.println(matrix[0][0]); // 1 - row 0, col 0
      System.out.println(matrix[1][2]); // 6 - row 1, col 2
      System.out.println(matrix[2][1]); // 8 - row 2, col 1

      System.out.println(matrix.length);    // 3 - number of rows
      System.out.println(matrix[0].length); // 3 - number of columns

  }//main method ends here

}//class ends here   ```

  • Terminal Output for 2D Array Program:

    • Compilation command: javac Sample.java

    • Execution command: java Sample

    • Console Output:text 1 6 8 3 3 &nbsp;&nbsp;&nbsp;&nbsp;

Key Characteristics and Memory Structure of Arrays

  • Homogeneous:

    • Every element contained within a specific array must be of the exact same data type (e.g., exclusively int, String, or double). Mixing types is prohibited by Java's type safety.

  • Fixed-size:

    • Arrays have a static, immutable size determined strictly at creation time.

    • Once an array is instantiated in memory, its length cannot be expanded or shrunk. Adding new elements beyond the allocated capacity requires instantiating an entirely new array.

  • Zero-based Indexing:

    • Elements are strictly indexed starting from position 00, running through to position size−1\text{size} - 1.

    • Attempting to access an index outside this range results in a runtime error (ArrayIndexOutOfBoundsException).

  • Contiguous Memory Allocation:

    • Array elements are assigned to adjacent, sequential memory locations in physical memory.

    • This contiguous layout enables constant-time (O(1)\mathcal{O}(1)) random access to any element via direct address calculation using the base memory address and index offset.