2D Arrays
Understanding 2D Arrays
- An array is a data structure that stores a fixed-size sequential collection of elements of the same type.
- A 2D array, also known as a matrix, stores data in a grid format. It has rows and columns, similar to a table.
- In Java, a 2D array is an array of arrays. Each row of the 2D array is a 1D array.
- 2D arrays are useful for representing data structures such as spreadsheets, grids, and games boards.
Declaration and Initialization
- To declare a 2D array in Java, you use the syntax:
type[][] arrayName;
- Initialization can take place at declaration, using nested curly braces
{}
. For example:int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
- The size of the array can be defined during initialization as
type arrayName[][] = new type[rows][cols];
Accessing Elements
- Elements of a 2D array can be accessed using their row index and column index. Remember, Java is zero-indexed, so indexing starts at 0.
- The syntax to access an element is:
arrayName[row][column]
- The value can be changed in a similar way:
arrayName[row][column] = newValue;
Traversing a 2D Array
- To traverse, or go through each element of a 2D array, we use nested loops. The outer loop iterates through the rows and the inner loop iterates through the columns.
- Sample syntax can be:
for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ System.out.print(arrayName[i][j] + " "); } System.out.println(); }
2D Array Methods and Properties
- You can use the
.length
property to get the number of rows in the 2D array. Note that this does not give the total number of elements in the array. - To get the number of columns, or the size of a particular row, we use
arrayName[row].length
- Methods that can be used with arrays include
Arrays.toString()
andArrays.deepToString()
for printing,Arrays.sort()
for sorting, andArrays.equals()
to check if two arrays are equal.