Two Dimensional Arrays in Java

Categorization of a 2-D array in Java are broadly of 2 types:

  1. Rectangular 2-D arrays.
  2. Jagged array/ array of arrays.

A rectangular 2-D array has each row of the same length i.e. number of columns in every row are same. Thus we can say Java’s rectangular 2-D array is same as 2D array given in C and C++.


Creating 2d Array

To create an array from the reference we will apply the same step as we do to create an object. The new keyword is used to create an array. Its syntax is:

datatype [][]variablename = new datatype [size][size];

The syntax can also be broken down into 2 separate lines as:

datatype [][]varaiblename;
variablename = new datatype [size][size];

In this step, memory allocation to the array variable takes place.


Accessing/initializing Data in 2d Array

To access or store data in a 2D array we can make use of iterative statements like while, do while, for or enhanced for loops.
Initialization of data in a 2-D array can be done in the following ways:

Approach 1:

int [][]ar = new int [2][3]; // Declaring 2D array having 2 rows and 3 columns
ar[0][0] = 10; // 0th row and 0th column element
ar[0][1] = 20; // 0th row and 1st column element

Approach 2:

int [][]ar = new int[][]{{10, 20, 30},{40, 50, 60}};

Note – Here is the creation and initialization of array is done with 2 rows and 3 columns.


Approach 3:

int [][]ar = {{10, 20, 30},{40, 50, 60}};

Note – Here is the creation and initialization of array is done with 2 rows and 3 columns.


Approach 4:

int [][]ar;                                     //creating reference of array
ar = new int[][]{{10, 20, 30},{40, 50, 60}};    //initializing with values without specifying size

Accessing of data in a 2-D array

We can do in the following ways:

Approach 1: Using for loop

int [][]ar = new int[][]{{10, 20, 30},{40, 50, 60}};
for(int i=0; i<ar.length; i++){    // traversing the rows
for(int j=0; j<ar[i].length; j++){ // traversing the columns
System.out.print(ar[i][j]+" ");
}
System.out.println();
}

Output:

10 20 30
40 50 60

Approach 2: Using enhanced for loop

int [][]ar = new int[][]{{10, 20, 30},{40, 50, 60}};
for(int []x:ar){          //traversing rows
for(int y:ax){            //traversing columns
System.out.print(y+" ");  //printing values
}
System.out.println();     //changing line 
}

Output:

10 20 30
40 50 60

Jagged Array

This is a special kind of 2-D array in java where we can have every row of different length. These arrays are very useful in those programming situations where we want to store the different number of values in each row. The main advantage of this approach is memory utilization will be efficient.

JaggedArray

Creation of the jagged array:

int [][]ar = new int[2][];  //specifying row size only
ar[0] = new int[4];         //specifying column size in row 1
ar[1] = new int[1];         //specifying column size in row 2

Initialization of jagged array:

Approach 1:

int [][]ar = new int[2][];     //declaration of array with 2 rows
ar[0] = new int[]{4, 5, 6};    //initialization of array with 3 columns in 1st row
ar[1] = new int[]{7};          //initialization of array with 1 columns in 2ndst row

Approach 2:

int [][]ar = new int[][]{{4, 5, 6},{7}};
//declaration and initialization or array with 2 rows
//in 1st row there are 3 columns
//in 2nd row there are 1 columns

Accessing data in a jagged array is similar to data access in a rectangular array in java.


Difference between length and length()

To know the size of an array we use length as final keyword and to determine the number of characters in a string we use length() function as the final method. For example:

int[] ar = new int[4]; //declaring an array
System.out.println("The size of the array is " + ar.length);        
String str = "Padhle"; //creating a String object
System.out.println("The size of the String is " + str.length());

Its output will be:

The size of the array is 4
The size of the String is 6

Possible Errors in Working with 2d Arrays

int[][] m;
int [][]m;
int m[][];
int []m[];
int[] m[];
int[] []m;
System.out.println(m);
System.out.println(m[0]);

//All above statements are valid

System.out.println(m[0][0]);      //invalid
m[givensize] = somevalue;         //invalid
m[givensize-1] = somevalue;       //valid


Storage of 2-D arrays in memory

Storing the 2-D array in memory is in the form of layers. One row after another is store in the linear main memory of a computer. If we know the first address of the memory location then we can locate an array element in the memory and retrieve the value at that location.

Formula:
ar[r][c]= base address+ wordsize*(r*(i)+c) for row wise storage.
ar[r][c]= base address+ wordsize*(r+c*j) for column wise storage.
where i and j are the dimention of array, and r and  c are the index of the array element.

This is all about the Java 2 dimensional arrays in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *