How to Create a 2D Array Dynamically in Java - onlyxcodes

Tuesday 9 July 2024

How to Create a 2D Array Dynamically in Java

Hello, Programmer in Java I'll demonstrate how to dynamically generate a 2D(two-dimensional array) array in Java in this tutorial.


In essence, a 2D array is an array of arrays. It is represented visually as a matrix or grid with rows and columns. Tabular data can be stored in Java using 2D arrays.


There are various phases involved in dynamically creating a 2D array in Java. In situations where the array size is unknown at build time, this procedure lets you define the array's size at runtime. This is a comprehensive tutorial on using and creating a dynamically sized 2D array in Java.


how to create 2D (two dimensional) array dynamically in java

Steps to Create a 2D Array Dynamically

Import Necessary Packages: Generally, fundamental Java array operations don't require any extra packages. However, depending on how complex the activities you plan to undertake are, you might need utility packages.


Declare the 2D Array: A 2D array must have its type of items declared when it is created.


Initialize the 2D Array: There are two ways to initialize an object: first, you can declare how many rows there are, and then you may specify how many columns each row has.


Populate the 2D Array: After initializing the array, values can be added to it.


Access and Modify Elements: The indexes of elements can be used to access and alter them.


Example Code:


Here’s a step-by-step example of creating, initializing, and working with a dynamically sized 2D array in Java.


public class Test 
{
    public static void main(String[] args) {
        // Step 1: Declare the 2D array
        int[][] dynamicArray;
        
        // Step 2: Determine the size at runtime (example size)
        int rows = 5; // number of rows
        int columns = 4; // number of columns
        
        // Step 3: Initialize the 2D array
        dynamicArray = new int[rows][columns];
        
        // Step 4: Populate the 2D array
        int value = 1; // some initial value
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                dynamicArray[i][j] = value++;
            }
        }
        
        // Step 5: Access and print elements of the 2D array
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(dynamicArray[i][j] + " ");
            }
            System.out.println();
        }
        
        // Example of modifying an element
        dynamicArray[2][3] = 99; // Change the value at row 3, column 4 to 99
        System.out.println("After modification:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(dynamicArray[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:


1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
After modification:
1 2 3 4
5 6 7 8
9 10 11 99
13 14 15 16
17 18 19 20

Logic Explanation of the Code


1. Declare the 2D Array: int[][] dynamicArray;


  • This line declares a 2D array of integers.

2. Determine Size at Runtime:


  • Here, the number of rows and columns is determined at runtime. For this example, we use fixed values (rows = 5 and columns = 4), but these could come from user input or other sources.

3. Initialize the 2D Array: dynamicArray = new int[rows][columns];


  • This line initializes the 2D array with the specified number of rows and columns.

4. Populate the 2D Array:


  • A nested loop is used to populate the array. The outer loop runs through each row, while the inner loop runs through each column of the current row.

5. Access and Print Elements:


  • Another nested loop is used to print the elements of the 2D array. This demonstrates how to access elements using their indices.

  • The example also includes modifying an element (dynamicArray[2][3] = 99;) and printing the array again to show the change.

Dynamic Initialization at Runtime

You can use the Scanner class to read values from the console to determine the size of the array based on user input.


import java.util.Scanner;
public class Test
{
    public static void main(String[] args) 
	{
        Scanner scanner = new Scanner(System.in);
        
        // Get size of the 2D array from user
        System.out.println("Enter number of rows: ");
        int rows = scanner.nextInt();
        System.out.println("Enter number of columns: ");
        int columns = scanner.nextInt();
        
        // Declare and initialize the 2D array
        int[][] dynamicArray = new int[rows][columns];
        
        // Populate the array
        System.out.println("Enter elements:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                dynamicArray[i][j] = scanner.nextInt();
            }
        }
        
        // Print the array
        System.out.println("The 2D array is:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(dynamicArray[i][j] + " ");
            }
            System.out.println();
        }
        
        scanner.close();
    }
}

Conclusion:

In Java, defining, initializing, and populating a 2D array dynamically includes runtime operations. When the size of the array cannot be specified at compile time, this flexibility is useful. You may quickly access and change the elements in the array by using loops. You can further improve the dynamic quality of your 2D arrays by including user input.


Learn More:

Can you print a string array in Java

Can you Remove an Element from an Array in Java

Can we compare 2 arrays in Java?

What is Array in Java with Example

What is the Long Array in Java with Example

What is Difference Between Array and ArrayList in Java

How to Add Value to an Array in Java

No comments:

Post a Comment

Post Bottom Ad