Intro | Declaring, Initializing | Accessing, Updating | Traversing | Algorithms |
Unit 8 - 2D Arrays Declaring and Initializing
2D Arrays Lesson
How to declare/initialize 2D arrays
// Boiler Plate Code public class Main { public static void main(String[] args) {
*/ (Intialize Array Here) */
// Display Array Code below
for(int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
} }
Main.main(null) 1) All in one
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
2) Empty array and manual input with indexes
// Declare a 3x3 empty 2D array
int[][] matrix = new int[3][3];
// Assign values to the 2D array using indexes
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
3) Nested For-Loop
int value = 1; // Start value
for (int i = 0; i < matrix.length; i++) { // Outer loop for rows
for (int j = 0; j < matrix[i].length; j++) { // Inner loop for columns
matrix[i][j] = value++; // Assign value and increment
}
}
Popcorn Hack 1 (Part 1):
- Intialize a 2D array of the people in your group grouped based on pairs with 3 different methods
- ex Array: [[Anusha, Vibha],[Avanthika, Matthew]]
String[][] method1 = {
{"Tarun", "Jon"},
{"Srijan", "Ian"}
};
String[][]method2=new String[2][2];
method2[0][0]="Tarun";
method2[0][1]="Jon";
method2[1][0]="Srijan";
method2[1][1]="Ian";
String[]names={"Tarun","Jon","Srijan","Ian"};
String[][]method3=new String[2][2];
int i=0;
int j=0;
for(int index=0;index<names.length;index++){
method3[i][j]=names[index];
j+=1;
if(j==2){
j=0;
i+=1;
}
}
System.out.println(Arrays.deepToString(method1));
System.out.println(Arrays.deepToString(method2));
System.out.println(Arrays.deepToString(method3));
[[Tarun, Jon], [Srijan, Ian]]
[[Tarun, Jon], [Srijan, Ian]]
[[Tarun, Jon], [Srijan, Ian]]