Create a two dimensional string array anArray[2][2]

Looks like this is what you want

    int columns = 2;
    int rows = 2;

    String[][] newArray = new String[columns][rows];
    newArray[0][0] = "France";
    newArray[0][1] = "Blue";

    newArray[1][0] = "Ireland";
    newArray[1][1] = "Green";

    for(int i = 0; i < rows; i++){
        for(int j = 0; j < columns; j++){
            System.out.println(newArray[i][j]);
        }
    }

Here I’ll explain the code:

This declares the size of your new 2D array. In Java (and most programming languages), your first value starts at 0, so the size of this array is actually 2 rows by 2 columns

    int columns = 2;
    int rows = 2;

Here you are using the type String[][] to create a new 2D array with the size defined by [rows][columns].

    String[][] newArray = new String[columns][rows];

You assign the values by its placement within the array.

    newArray[0][0] = "France";
    newArray[0][1] = "Blue";

    newArray[1][0] = "Ireland";
    newArray[1][1] = "Green";

Looping through i would loop through the rows, and looping through j would loop through the columns. This code loops through all rows and columns and prints out the values in each index.

    for(int i = 0; i < rows; i++){
        for(int j = 0; j < columns; j++){
            System.out.println(newArray[i][j]);
        }
    }

Alternatively, assignment can be a one-liner:

    String[][] newArray = {{"France", "Blue"}, {"Ireland", "Green"}};

But I don’t like this way, as when you start dealing with larger sets of data (like 10,000+ points of data with many columns), hardcoding it in like this can be rough.

Leave a Comment