Java Two Dimensional Array Program

This article is created to cover a program in Java, based on two dimensional array. A two dimensional array is basically an array of array. For example:

arr[4][2]

is a two dimensional array, where there are four one dimensional array of 2 elements each. Let's take an example:

public class CodesCracker
{
   public static void main(String[] args)
   {
      int[][] arr = {{1, 2},{3, 4},{5, 6},{7, 8}};
      
      System.out.println("Array's Elements with its indexes: ");
      for(int i=0; i<4; i++)
      {
         for(int j=0; j<2; j++)
            System.out.print("arr["+i+"]["+j+"] = " +arr[i][j]+"\t");
         System.out.print("\n");
      }
   }
}

The snapshot given below shows the sample output produced by above program, on two-dimensional array in Java:

two dimensional array program example java

Now let's create another program, after modifying the previous one, that allows user to define the dimension or row and column size of the array too, along with its elements, of course:

import java.util.Scanner;

public class CodesCracker
{
   public static void main(String[] args)
   {
      int row, col, i, j;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter Row size: ");
      row = scan.nextInt();
      System.out.print("Enter column Size: ");
      col = scan.nextInt();
      
      int[][] arr = new int[row][col];
      
      System.out.print("\nEnter " +(row*col)+ " Elements: ");
      for(i=0; i<row; i++)
      {
         for(j=0; j<col; j++)
            arr[i][j] = scan.nextInt();
      }
      
      System.out.println("\nArray's Elements with its indexes: ");
      for(i=0; i<row; i++)
      {
         for(j=0; j<col; j++)
            System.out.print("arr["+i+"]["+j+"] = " +arr[i][j]+"\t");
         System.out.print("\n");
      }
   }
}

Here is its sample run with user input 4 as row size, 2 as column size, and 1, 2, 3, 4, 5, 6, 7, 8 as elements for the array:

java two dimensional program

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »


Liked this post? Share it!