a shot of dev knowledge

Related tags

How to use 2-D arrays in Java

Similar to a 1-D array, a 2-D array is a collection of data cells. 2-D arrays work in the same way as 1-D arrays in most ways; however, unlike 1-D arrays, they allow you to specify both a column index and a row index.

All the data in a 2D array is of the same type.

svg viewer

Declaring 2-D arrays

Similar to the 1-D array, we must specify the data type, the name, and the size of the array. The size of a 2-D array is declared by the number of rows and number of columns. For example:

class Testarray{  
  public static void main(String args[]){
    int number_of_rows=6;
    int number_of_columns=5;
    int arr[][] = new int[number_of_rows][number_of_columns];
  }
}  

In the example above, arr is the name of the array.

The total number of elements in this 2-D array is:

number_of_rows * number_of_columns

So the total number elements in arr are 30.


Initializing 2-D arrays

You can also initialize an array while declaring it in the following manner:

// initializing an array on declaration
int arr[][] = {{1, 2, 3},{4, 5, 6},{7,8,9} };

Accessing 2-D arrays

Like 1-D arrays, you can access individual cells in a 2-D array by using subscripts that specify the indexes of the cell you want to access. However, you now have to specify two indexes instead of one. The expression looks like this:

arr[2][3]=5;
System.out.println(arr[2][3]); // prints out 5
  • 2 is the row index
  • 3 is the column index
  • 5 is the value at this index

You can also find the length of a row or a column using the following syntax:

arr[2][].length; // prints length of 3rd row
arr[][0].length; // prints length of 1st column
svg viewer
indexes of 2-D array

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring