Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Creating Two Dimensional Arrays
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Let's expand our array conversation to two-dimensional arrays. Spreadsheets, web browser screens, images, and many other types of data are in a 2D format, which is why we need arrays that can handle this type of data. A 2D array is laid out in a grid like graph paper, meaning each element is still housed in its own cell like in a 1D array. However, that element is now represented by two different indexes that are both needed in order to specify that cell. Take a look at the 2D arrays below.
TwoDimensionalArraysExample.java
package exlcode;
public class TwoDimensionalArraysExample {
public static int[][] exampleVariableOne = new int[3][4];
public static int[][] exampleVariableTwo = {{0, 1, 2, 3, 4}, {4, 5, 6, 7, 8}};
public static boolean[][] exampleVariableThree = {{true, false, false, true}, {false, false, true, true}};
public static void main(String[] args) {
exampleVariableOne[1][2] = 10000;
// the default value for int[][] elements when declared is also 0
System.out.println(exampleVariableOne[1][1]);
System.out.println(exampleVariableTwo[1][3]);
System.out.println(exampleVariableThree[0][2]);
}
}
Similar to 1D arrays, the index of both row and column start at 0. The first square bracket after the array name specifies the row while the second one dictates the column. All indexes start at 0, so varOne[0][0] specifies the first row and the first column. If you have varOne[3][1], you are indicating the element that exists in the fourth row and the second column. Like 1D arrays, all the elements must have the same datatype. Initializing a 2D array is also very similar to initializing a 1D array.
datatype[][] arrayname = new datatype[3][1];
Creates a 2D array with three rows and one column.
Which of the following statements assigns the letter 'A' to the 3rd row and 1st column of the two-dimensional array?
Note that there is no "0th column" or "0th row".