Manipulating 2D Arrays public Class ArrayPractice { public static void main(String[] args) { int[][] array = {{3, 5, 7}, {500, 250, 125, 784, 267}, {23, 25};

Manipulating 2D Arrays public Class ArrayPractice { public static void main(String[] args) { int[][] array = {{3, 5, 7}, {500, 250, 125, 784, 267}, {23, 25}}; // Update the first array in the 2D array to the length of the 2D array: updateValue(array[0], array.length); // Update the second array in the 2D array to the sum of the first and last values in the array: updateValue(array[1], array[1][0] + array[1][array[1].length – 1]); // Update the third array in the 2D array to the sum of the first and last values in the array: updateValue(array[2], array[2][0] + array[2][array[2].length – 1]); printArray(array); } public static void updateValue(int[] array, int value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void printArray(int[][] array) { for (int[] row : array) { for (int num : row) { System.out.print(num + ” “); } System.out.println(); } } }

The Correct Answer and Explanation is:

Correct Output:

The Java program outputs the following after execution:

CopyEdit3 3 3 
767 767 767 767 767 
48 48 

Explanation:

This Java program demonstrates how to manipulate elements in a 2D array by updating its inner arrays using a helper method and then printing the modified array.

✅ Step-by-Step Breakdown:

javaCopyEditint[][] array = {
    {3, 5, 7},
    {500, 250, 125, 784, 267},
    {23, 25}
};

This creates a 2D array (array) with three 1D arrays of different lengths (a jagged array).


🔁 updateValue(array[0], array.length);

This line updates all elements of the first inner array ({3, 5, 7}) to the value of array.length, which is 3 (since there are 3 inner arrays).

Result:

javaCopyEdit{3, 3, 3}

➕ updateValue(array[1], array[1][0] + array[1][array[1].length - 1]);

This updates all elements of the second inner array ({500, 250, 125, 784, 267}) to the sum of the first and last elements:
500 + 267 = 767

Result:

javaCopyEdit{767, 767, 767, 767, 767}

➕ updateValue(array[2], array[2][0] + array[2][array[2].length - 1]);

This updates all elements of the third inner array ({23, 25}) to:
23 + 25 = 48

Result:

javaCopyEdit{48, 48}

🖨️ printArray(array);

Prints each row of the 2D array with updated values, each element separated by spaces and each row on a new line.


🔚 Conclusion:

This program reinforces understanding of:

  • 2D array indexing
  • Updating array elements using helper methods
  • Iterating over jagged arrays
  • Accessing first and last elements with indexing

Such exercises are foundational in learning how to navigate and manipulate multidimensional structures in Java.

Scroll to Top