2D Arrays

A 2D array is an array of arrays, and a type of multidimensional array. To create a 2D array, you write the type of the class, followed by the name, and the values.

College Board

Unit 8 is worth 7.5-10% of the college board test, so it is not worth a huge amount. However, it is still important to understand how they work and when they can be utilized.

Learning Objectives

  • 8.1 2D Arrays
    • Represent collections of related primitive or object reference data using two-dimensional (2D) array objects.
  • 8.2 Traversing 2D Arrays
    • For 2D array objects:
      • a. Traverse using nested for loops.
      • b. Traverse using nested enhanced for loops.

Creating A 2D Array

The first step is to initialize the array. To do this, specify the type, followed by "[][]", followed by the name of the 2D array. Examples:

int[][] numbers;
String[][] names;
char[][] letters;
float[][] floats;
double[][] doubles;
Object[][] objects;

Initializing a 2D Array

Then you must give it a value, by initializing the 2D array. There are two ways to initialize a 2D array. Method 1: You can initialize the array by giving it values Method 2: You can also initialize it by giving it the size

int[][] numbers1 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};//method 1:
int[][] numbers2 = new int[4][3]; //method 2: Creates array with four rows and 3 columns 
String[][] names1 = {{"John","James","Jay"},{"Melissa","May","Maggie"},{"Bob","Burt","Billy"}}; //method 1
String[][] names2 = new String[2][2]; //method2: Creates array with 2 rows and 2 columns
char[][] letters1 = {{'a','b','c'},{'d','e','f','g','h'}}; //method 1
char[][] letters2 = new char[2][3]; //method 2: Creates array with 2 rows and 3 columns

Note, that when you initialize a 2D array using method 1, each row can have a different number of columns, ie, each array within the array can have a different number of values.

Iteration

To iterate through a normal array, you would could use a for loop, as demonstrated below to print the alphabet. You would iterate through the first array(row), then use another for loop nested within the first that iterates through the second arrays(columns).

String[][] alphabet = {{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "="},
{"q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "\\"},
{"a", "s", "d", "f", "g", "h", "j", "k", "l"},
{"z", "x", "c", "v", "b", "n", "m", ",", ".", "/"}};
for(int i = 0;i<alphabet.length;i++){
    for(int j = 0; j < alphabet[i].length;j++){ //nested for loops
        System.out.print(alphabet[i][j]+" ");
    }
    System.out.println(" ");
}
1 2 3 4 5 6 7 8 9 0 - =  
q w e r t y u i o p [ ] \  
a s d f g h j k l  
z x c v b n m , . /  

In this way, you can print all the values of a certain 2D array.

Accessing and Changing Elements of 2D Arrays

You can change elements or access elements in 2D arrays by using the indexes. For example, to access the 2nd row, and 3 column, use [1][2]

int[][] numbers = new int[2][2]; //method 2: Creates array with two rows and two columns
numbers[0][0] = 1;
numbers[0][1] = 4;
numbers[1][0] = 9;
numbers[1][1] = 16;
for(int i = 0;i<numbers.length;i++){
    for(int j = 0; j < numbers[i].length;j++){ //nested for loops
        System.out.print(numbers[i][j]+" ");
    }
    System.out.println(" ");
}
1 4  
9 16  

Displaying Contents of Array Vertically and Horizontally

Here, I've created a 2D array with 10 rows and 10 columns. Then, I used nested for loops to initialize values for each value in each row and column to the product of the row and column numbers.

int[][]products = new int [10][10]; //creating 2D Array
for(int i = 0;i<products.length;i++){
    for(int j = 0; j < products[i].length;j++){ 
        products[i][j] = i*j; //initializing values for array
    }
}

System.out.println("Printing out values in a pattern/grid design:\n");
for(int i = 0;i<products.length;i++){
    for(int j = 0; j < products[i].length;j++){ 
        System.out.print(products[i][j]+" ");
    }
    System.out.println(" ");
}
System.out.println("\nPrinting out values horizontally:\n");
for(int i = 0;i<products.length;i++){
    for(int j = 0; j < products[i].length;j++){ 
        System.out.print(products[i][j]+" ");
    }
}
System.out.println("\n\nPrinting out values vertically:\n");
for(int i = 0;i<products.length;i++){
    for(int j = 0; j < products[i].length;j++){ 
        System.out.println(products[i][j]+" ");
    }
}
Printing out values in a pattern/grid design:

0 0 0 0 0 0 0 0 0 0  
0 1 2 3 4 5 6 7 8 9  
0 2 4 6 8 10 12 14 16 18  
0 3 6 9 12 15 18 21 24 27  
0 4 8 12 16 20 24 28 32 36  
0 5 10 15 20 25 30 35 40 45  
0 6 12 18 24 30 36 42 48 54  
0 7 14 21 28 35 42 49 56 63  
0 8 16 24 32 40 48 56 64 72  
0 9 18 27 36 45 54 63 72 81  

Printing out values horizontally:

0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36 0 5 10 15 20 25 30 35 40 45 0 6 12 18 24 30 36 42 48 54 0 7 14 21 28 35 42 49 56 63 0 8 16 24 32 40 48 56 64 72 0 9 18 27 36 45 54 63 72 81 

Printing out values vertically:

0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
0 
2 
4 
6 
8 
10 
12 
14 
16 
18 
0 
3 
6 
9 
12 
15 
18 
21 
24 
27 
0 
4 
8 
12 
16 
20 
24 
28 
32 
36 
0 
5 
10 
15 
20 
25 
30 
35 
40 
45 
0 
6 
12 
18 
24 
30 
36 
42 
48 
54 
0 
7 
14 
21 
28 
35 
42 
49 
56 
63 
0 
8 
16 
24 
32 
40 
48 
56 
64 
72 
0 
9 
18 
27 
36 
45 
54 
63 
72 
81 

Displaying Backwards and Upside Down

Here, I've created a 2D array with 10 rows and 10 columns. Then, I used nested for loops to initialize values for each value in each row and column to the sum of the row and column numbers.

int[][]sums = new int [10][10]; //creating 2D Array
for(int i = 0;i<sums.length;i++){
    for(int j = 0; j < sums[i].length;j++){ 
        sums[i][j] = i+j; //initializing values for array
    }
}

System.out.println("Printing out values forward");
for(int i = 0;i<products.length;i++){
    for(int j = 0; j < products[i].length;j++){ 
        System.out.print(products[i][j]+" ");
    }
    System.out.println(" ");
}

System.out.println("\n\nPrinting out values backward");
for(int i = products.length-1;i>=0;i--){
    for(int j = products[i].length-1; j >= 0;j--){ 
        System.out.print(products[i][j]+" ");
    }
    System.out.println(" ");
}
Printing out values forward
0 0 0 0 0 0 0 0 0 0  
0 1 2 3 4 5 6 7 8 9  
0 2 4 6 8 10 12 14 16 18  
0 3 6 9 12 15 18 21 24 27  
0 4 8 12 16 20 24 28 32 36  
0 5 10 15 20 25 30 35 40 45  
0 6 12 18 24 30 36 42 48 54  
0 7 14 21 28 35 42 49 56 63  
0 8 16 24 32 40 48 56 64 72  
0 9 18 27 36 45 54 63 72 81  


Printing out values backward
81 72 63 54 45 36 27 18 9 0  
72 64 56 48 40 32 24 16 8 0  
63 56 49 42 35 28 21 14 7 0  
54 48 42 36 30 24 18 12 6 0  
45 40 35 30 25 20 15 10 5 0  
36 32 28 24 20 16 12 8 4 0  
27 24 21 18 15 12 9 6 3 0  
18 16 14 12 10 8 6 4 2 0  
9 8 7 6 5 4 3 2 1 0  
0 0 0 0 0 0 0 0 0 0  
int[][]sums = new int [10][10]; //creating 2D Array
for(int i = 0;i<sums.length;i++){
    for(int j = 0; j < sums[i].length;j++){ 
        sums[i][j] = i+j; //initializing values for array
    }
}

System.out.println("Rows forward, columns backward");
for(int i = 0;i<products.length;i++){
    for(int j = products[i].length-1; j >= 0;j--){ 
        System.out.print(products[i][j]+" ");
    }
    System.out.println(" ");
}

System.out.println("\n\nRows backward, columns forward");
for(int i = products.length-1;i>=0;i--){
    for(int j = 0; j <products[i].length;j++){ 
        System.out.print(products[i][j]+" ");
    }
    System.out.println(" ");
}
Rows forward, columns backward
0 0 0 0 0 0 0 0 0 0  
9 8 7 6 5 4 3 2 1 0  
18 16 14 12 10 8 6 4 2 0  
27 24 21 18 15 12 9 6 3 0  
36 32 28 24 20 16 12 8 4 0  
45 40 35 30 25 20 15 10 5 0  
54 48 42 36 30 24 18 12 6 0  
63 56 49 42 35 28 21 14 7 0  
72 64 56 48 40 32 24 16 8 0  
81 72 63 54 45 36 27 18 9 0  


Rows backward, columns forward
0 9 18 27 36 45 54 63 72 81  
0 8 16 24 32 40 48 56 64 72  
0 7 14 21 28 35 42 49 56 63  
0 6 12 18 24 30 36 42 48 54  
0 5 10 15 20 25 30 35 40 45  
0 4 8 12 16 20 24 28 32 36  
0 3 6 9 12 15 18 21 24 27  
0 2 4 6 8 10 12 14 16 18  
0 1 2 3 4 5 6 7 8 9  
0 0 0 0 0 0 0 0 0 0  

Homework

  • Create a class for 2D array learning.
  • Create a method too initialize a 2D array with arbitrary values
  • Create a method to reverse the 2D array and print out the values
  • Create a method that asks for the input of a position and it returns the corresponding value
  • Create a method that multiplies each value in a row and then adds all the products together
  • Create a new object to test out each method in the main function
public class Homework{ // Create a class for 2D array learning.
   
    private int[][] adis;
    private int [][] rohans; // reversed 2D array


    public Homework(){

        adis = new int[6][6];
        rohans = new int[6][6];  // Initialize a 2D array with arbitrary values

    }


    public void init(){ // Initialize a 2D array and set arbitrary values

        for(int i = 0; i < adis.length; i++){

            for(int j = 0; j < adis[i].length; j++){

                adis[i][j] = (int) (Math.random() * (100 - 1)) + 1; 
            }

        }

    }
    
    public void print(int[][] temp){

        for(int i = 0; i < temp.length; i++){

            for(int j = 0; j < temp[i].length; j++){

                System.out.print(temp[i][j] + " "); 
            }
            
            System.out.println(); 

        }
    }

    public void reverse(){ // Create a method to reverse the 2D array and print out the values

        for(int i = 0; i < adis.length; i++){

            for(int j = 0; j < adis[i].length; j++){

                rohans[adis.length-1-i][adis[i].length-1-j] = adis[i][j];

            }

        }

    }

    public String inputIndex(){  // Create a method that asks for the input of a position and it returns the corresponding value

        Scanner sc = new Scanner(System.in);

        System.out.println("Row 1 - 5: ");
        int num1 = sc.nextInt()-1;

        System.out.println("Column 1 - 5: ");
        int num2 = sc.nextInt()-1;

        return ("Value:" + adis[num1][num2]);
    }

    public void productSum(){ // Create a method that multiplies each value in a row and then adds all the products together
        int n = 1;
        int sum = 0;
        for(int i = 0; i < adis.length; i++){
            for(int j = 0; j < adis[i].length; j++){
                n *= adis[i][j];
            }
            sum += n;
            n = 1;
        }
        System.out.println("Product Sum: " + sum);
    }

    public static void main(String[] args) { // Create a new object to test out each method in the main function
        Homework b = new Homework();
        b.init();
        System.out.println("Original Array");
        b.print(b.adis);

        System.out.println(" ");
        b.reverse();
        System.out.println("Reversed Array");
        b.print(b.rohans);

        System.out.println();
        System.out.println(b.inputIndex());

        System.out.println();
        b.productSum();
    }
}

Homework.main(null);
Original Array
70 62 35 15 18 62 
38 72 43 46 26 8 
21 82 48 74 30 23 
85 44 29 30 83 85 
47 60 17 25 35 97 
13 53 3 66 34 32 
 
Reversed Array
32 34 66 3 53 13 
97 35 25 17 60 47 
85 83 30 29 44 85 
23 30 74 48 82 21 
8 26 46 43 72 38 
62 18 15 35 62 70 

Row 1 - 5: 
Column 1 - 5: 
Value:44

Product Sum: 702032692
class MonkeyLoop {
    String [][] monkeys;
    String [][] cthulhus;
    //hint: missing code


    public MonkeyLoop() {
        monkeys = new String[][]{

                {
                        "ʕง ͠° ͟ل͜ ͡°)ʔ ",      //[0][0] eyes
                },

                {
                        "  \\_⏄_/  ",      //[1][0] chin

                },

                {
                        "  --0--   ",       //[2][0] body

                },

                {
                        "  ⎛   ⎞   "        //[3][0] legs
                },


        };

        cthulhus = new String[][]{
            {
                    "⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⡀⠀⠀⠀⠀⠀⠀⢎⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ʕง ͠° ͟ل͜ ͡°)ʔ ",
                    "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⢱⠀⠀⢀⣤⡀⠀⠀⢣⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀  \\_⏄_/  ",
                    "⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⠻⠉⣧⣿⣿⣿⠀⠀⢸⠇⠀⠐⠉⡆⠀⠀⠀⠀⠀⠀  --0--   ",
                    "⠀⠀⠀⠀⢀⠔⠒⢦⠀⢻⡄⠀⢿⣻⣿⡿⢀⣴⣋⣄⣄⣌⣠⠃⠀⠀⠀⠀⠀⠀  ⎛   ⎞   ",
                    "⠀⠀⠀⠀⠈⠀⢀⡞⠀⠈⠛⣷⣾⣿⣿⣿⣿⣿⣯⣥⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀         ",
                    "⠀⠀⠀⠀⠀⠀⠈⠷⣦⣴⡾⢿⣿⡿⢿⣿⣋⣽⠶⢦⠙⢷⡀⠀⠀⠀⠀⠀⠀⠀         ",
                    "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⡏⢀⡆⠈⠉⠁⡄⠈⡇⠘⢇⠀⢈⡆⠀⠀⠀⠀         ",
                    "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡯⠀⠸⠁⠀⠀⠸⣧⡀⡇⠀⠈⠉⠉⠀⠀⠀⠀⠀         ",
                    "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣇⡴⠁⠀⠀⠀⠀⠙⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀          "
            },
        };
    }

    public void printPoem() {
        System.out.println();
        System.out.println("A story of a Monkey and Cthulhus");
        int monkeyCount = monkeys.length;
        for (int i = 1; i >= 1; i--)
        {
            for (int row = 0; row < monkeyCount; row++) {  //cycles through "cells" of 2d array
                for (int col = 0; col < monkeys[row].length; col++) {
                    System.out.print(monkeys[row][col] + " ");
                }

                //this new line gives separation between stanza of poem
                System.out.println();
            }
        }
            //hint: missing code, another for loop
        int cthulhuCount = cthulhus[0].length;
        for (int col1 = 0; col1 < cthulhuCount; col1++) {  //cycles through "cells" of 2d array
        for (int row1 = 0; row1 < 1; row1++){
            System.out.print(cthulhus[row1][col1]);
        }
        // Spacer
        System.out.println();
        }
        // System.out.println(cthulhuCount);
        System.out.println("0000000000000000000000000000000000");
        System.out.println("             THE END              ");
    }


    public static void main(String[] args)  {
        new MonkeyLoop().printPoem();
    }
}
MonkeyLoop.main(null);
A story of a Monkey and Cthulhus
ʕง ͠° ͟ل͜ ͡°)ʔ  
  \_⏄_/   
  --0--    
  ⎛   ⎞    
⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⡀⠀⠀⠀⠀⠀⠀⢎⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ʕง ͠° ͟ل͜ ͡°)ʔ 
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⢱⠀⠀⢀⣤⡀⠀⠀⢣⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀  \_⏄_/  
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⠻⠉⣧⣿⣿⣿⠀⠀⢸⠇⠀⠐⠉⡆⠀⠀⠀⠀⠀⠀  --0--   
⠀⠀⠀⠀⢀⠔⠒⢦⠀⢻⡄⠀⢿⣻⣿⡿⢀⣴⣋⣄⣄⣌⣠⠃⠀⠀⠀⠀⠀⠀  ⎛   ⎞   
⠀⠀⠀⠀⠈⠀⢀⡞⠀⠈⠛⣷⣾⣿⣿⣿⣿⣿⣯⣥⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀         
⠀⠀⠀⠀⠀⠀⠈⠷⣦⣴⡾⢿⣿⡿⢿⣿⣋⣽⠶⢦⠙⢷⡀⠀⠀⠀⠀⠀⠀⠀         
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⡏⢀⡆⠈⠉⠁⡄⠈⡇⠘⢇⠀⢈⡆⠀⠀⠀⠀         
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡯⠀⠸⠁⠀⠀⠸⣧⡀⡇⠀⠈⠉⠉⠀⠀⠀⠀⠀         
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣇⡴⠁⠀⠀⠀⠀⠙⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀          
0000000000000000000000000000000000
             THE END