2-Dimensional Arrays in Java

Today, we started to cover 2-dimensional arrays in Java. I decided to start with something very easy:

2-D Array Visual
2-D Array Visual

We have an array with 2 rows and 3 columns. Like all things in Java, we start counting our indices at 0.

As such, the value of [0][0] is Vanilla and [1][0] is Ice Cream. Note that the first number in the reference points to the row and the second number in the reference points to the column.

import java.util.*;
public class TwoDArrays {
    public static void main(String[] args){
        String[][] myBigArray = new String [][] {
            {"Vanilla ", "Chocolate ", "Strawberry "},
            {"Ice Cream", "Cookie", "Candy"}
        };
        System.out.println(myBigArray[0][0] + myBigArray[1][0]);
        System.out.println(myBigArray[0][1] + myBigArray[1][0]);
        System.out.println(myBigArray[0][2] + myBigArray[1][0]);
        
        System.out.println(myBigArray[0][0] + myBigArray[1][1]);
        System.out.println(myBigArray[0][1] + myBigArray[1][1]);
        System.out.println(myBigArray[0][2] + myBigArray[1][1]);
        
        System.out.println(myBigArray[0][0] + myBigArray[1][2]);
        System.out.println(myBigArray[0][1] + myBigArray[1][2]);
        System.out.println(myBigArray[0][2] + myBigArray[1][2]);
    }
}

Line 4 is where we created the 2-dimensional array named “myBigArray”.

Lines 5 and 6 are where we populated the array. Note that line 5 is the first row and line 6 is the second row.

Lines 8 through 18 are where we are outputting text that is “fed” by the 2-D array.

Line 8 concatenates [0][0] with [1][0] which is Vanilla and Ice Cream.

Line 9 concatenates [0][1] with [1][0] which is Chocolate and Ice Cream.

Line 10 concatenates [0][2] with [1][0] which is Strawberry and Ice Cream.

Line 12 concatenates [0][0] with [1][1] which is Vanilla and Cookie.

Line 13 concatenates [0][1] with [1][1] which is Chocolate and Cookie.

Line 14 concatenates [0][2] with [1][1] which is Strawberry and Cookie.

Line 16 concatenates [0][0] with [1][2] which is Vanilla and Candy.

Line 17 concatenates [0][1] with [1][2] which is Chocolate and Candy.

Line 18 concatenates [0][2] with [1][2] which is Strawberry and Candy.