Basics of 2D Arrays

  • Multi dimensional
  • 7.5-10% of the AP exam
  • Compared to a normal array, you have two pairs of brackets

Creation

Make sure to put two pairs of brackets when creating a 2D Array

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

Initiation

Sets values to each new array with initiation

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];

Iteration Example

Uses for loop print alphabet. Iterates through first array, the row, then the other loop, which is the column

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 , . /