HIDE NAV

2D Array - In Class

Coded Mon. 9-23-24

The below command line program demonstrates the basics of 2-dimensional (2D) array declaration, initialization and access. Similar processes are shown for single variables and 1D arrays for comparison.
This code also show the common nested for loop style frequently used to initialize or access a 2D Array.

Main.java


public class Main {
    public static void main(String[] args) {
       
        //1d example
        char[] dataRow; //array declaration - not ready to use
        dataRow = new char[12]; //call constructor to set up
        //assignments in a loop
        for(int i = 0; i < dataRow.length; i++){
            dataRow[i] = '*';
        }
        //single assignment
        dataRow[4] = 'Z';

        //printing an array with a loop
        for (int i = 0; i < dataRow.length; i++) {
            System.out.print("[" + i + "]: " + dataRow[i]);
            System.out.print("   ");
        }
        
        //2d array of characters
        char[][] dataGrid;
            int w = 3;
            int h = 4;
        dataGrid = new char[w][h];
        
        //
        System.out.println("2d array");
        System.out.println("---------");

        for(int i = 0; i < w; i++){
            for(int j = 0; j < h; j++){
                dataGrid[i][j] = '*';
            }
        }

        //assigning a single value
        dataGrid[2][1] = 'Z';
        
        
        //NOTE: this will print 'side-ways' with height 3 and width 4
        for(int i = 0; i < w; i++){
            for(int j = 0; j < h; j++){
                System.out.print(dataGrid[i][j]);
                System.out.print("  ");
            }
            System.out.print('\n');
        }
    }
}