Two dimensional array in java

Let’s learn two dimensional array in java.

Two dimensional array in java

Two dimensional array is nothing but array of arrays. It is a collection of various elements of same data type.

Elements or data in two dimensional array are stored in rows and columns. To create a two dimensional array first we need to specify the data type that we are going to store in that array.

two dimensional array in java

Here we are going to store integer values. Next thing, we need to allocate memory so that we can store some values in that allocated array.

To do that first we need to write like this,

student = new int[2][3];

After writing above statement all elements are going to contain default value of zero.

Also read – multidimensional array in java

Because when you create an array in java they will be initialized with default values depending on data type (here data type is integer).

If our array was string then it would contain “null” value. Similarly for different data types we have different default values.

Before going to example let’s learn how to assign values to two dimensional array in java. To do that first write array name then row index, column index lastly assign value as shown below,

// declaring and assigning value in one line
int[][] student = {{2,4,6},{8,10,12}};

OR

student[0][0] = 2;
student[0][1] = 4;
student[0][2] = 6;
student[1][0] = 8;
student[1][1] = 10;
student[1][2] = 12;

In the below java program user enters row length and column length which will be stored in row and length variables using sc.nextInt() method of Scanner class.

Then sc.nextInt() method reads the number from two for loops and inserts element at student[a][b].

Let’s see simple two-dimensional array program in java or using scanner or using for loop.

import java.util.Scanner;
public class TwoDimensionalDemo 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter row length : ");
      int row = sc.nextInt();
      System.out.println("Please enter column length : ");
      int column = sc.nextInt();
      // array declaration
      int[][] student = new int[row][column];      
      System.out.println("Please enter " + row * column + " elements in array :\n");
      for(int a = 0; a < row; a++)
      {
         for(int b = 0; b < column; b++)
         {
            student[a][b] = sc.nextInt();
         }
      }
      System.out.println("Elements in array :\n");
      for(int a = 0; a < row; a++)
      {
         for(int b = 0; b < column; b++)
         {
            System.out.println("Row ["+ a +"] : Column ["+ b +"] : " + student[a][b]);
         }
      }
      sc.close();
   }
}


Output:

Please enter row length : 2
Please enter column length : 3
Please enter 6 elements in array :
2
4
6
8
10
12
Elements in array :
Row [0] : Column [0] : 2
Row [0] : Column [1] : 4
Row [0] : Column [2] : 6
Row [1] : Column [0] : 8
Row [1] : Column [1] : 10
Row [1] : Column [2] : 12


2D array example program

2 dimensional array in java can also be defined as an array of objects and primitive data types. Let’s see an example,

// Two dimensional array of primitive type
public class PrimitiveTypeDemo
{
   public static void main(String[] args) 
   {
      int[][] num = new int[2][3];
      for(int a = 0; a < num.length; a++) 
      {
         for(int b = 0; b < num[a].length; b++) 
         {
            num[a][b] = b;
            System.out.print(num[a][b] + " ");
         }
         System.out.println("");
      }
   }
}


Output:

0 1 2
0 1 2


Two dimensional array of objects

// Two dimensional array of objects
public class ArrayofObjectsDemo 
{
   public static void main(String[] args) 
   {
      String[][] arrDemo = new String[3][4];
      for(int a = 0; a < arrDemo.length; a++) 
      {
         for(int b = 0; b < arrDemo[a].length; b++) 
         {
            arrDemo[a][b] = "string" + b;
            System.out.print(arrDemo[a][b] + " ");
         }
         System.out.println("");
      }
   }
}


Output:

string0 string1 string2 string3
string0 string1 string2 string3
string0 string1 string2 string3


Two dimensional string array in java example

2D array in java can be used to print elements of two dimensional string array in java. Let’s see an example,

public class TwoDimensionalString 
{
   public static void main(String[] args) 
   {
      String[][] strNames = new String[][]{{"virat", "dhoni"},{"ishant", "umesh"},{"pujara","ajinkya"}};
      System.out.println("two dimensional string array elements :\n");    
      for(int a = 0; a < 3; a++) 
      {
         for(int b = 0; b < 2; b++) 
         {
            System.out.println("str["+ a +"]["+ b +"] : " + strNames[a][b]);
         }
      }
   }
}


Output:

two dimensional string array elements :

str[0][0] : virat
str[0][1] : dhoni
str[1][0] : ishant
str[1][1] : umesh
str[2][0] : pujara
str[2][1] : ajinkya


How to populate

Now let’s learn how to populate a 2d array with numbers. In the below java program we first loop to populate given array and then print given array values.

public class TwoDimensionalDemo
{
   public static void main(String[] args) 
   {
      int[][] arrNumbers = new int[3][3];
      // populate arrNumbers
      for(int row = 0; row < arrNumbers.length; row++) 
      {
         for(int column = 0; column < arrNumbers[row].length; column++) 
         {
            arrNumbers[row][column] = row * column;
         }
      }
      // printing each row and column
      for(int row = 0; row < arrNumbers.length; row++) 
      {
         for(int column = 0; column < arrNumbers[row].length; column++) 
         {
            arrNumbers[row][column] = row * column;
            System.out.print(arrNumbers[row][column] + "\t");
         }
         System.out.println();
      }
   }
}


Output:

0 0 0
0 1 2
0 2 4


how to add two dimensional array

Here’s the java program to add two matrix

public class HowToAdd
{
   public static void main(String[] args) 
   {
      int row = 2, col = 3;
      int[][] arrFirst = { {1, 3, 5}, {7, 9, 2} };
      int[][] arrSecond = { {4, 6, 8}, {1, 3, 5} };
      int[][] add = new int[row][col];
      for(int a = 0; a < row; a++) 
      {
         for(int b = 0; b < col; b++) 
         {
             add[a][b] = arrFirst[a][b] + arrSecond[a][b];
         }
      }
      System.out.println("Add two dimensional array in java: ");
      for(int[] r : add) 
      {
         for(int c : r) 
         {
            System.out.print(c + "    ");
         }
         System.out.println();
      }
   }
}


Output:

Add two dimensional array in java:
5 9 13
8 12 7

Two dimensional array is one of the most common interview questions. Hope this post would be helpful for freshers.