Two-dimensional array JAVA

  1. Home
  2. Blog
  3. Two-dimensional array JAVA

Two-dimensional array JAVA

We can declare a two dimensional array and directly store elements at the time of its declaration as shown below:

int numbers[][]={{23,45,57,24,74},{34,67,23,55,23},{34,74,24,46,78},{23, 56,87, 89,96}, {95, 03, 45, 99,56}};

Here int represents integer type elements stored into array and array name is ‘numbers’. ‘int’ is the datatype for all elements represented inside “{” and “}” braces because an array is a collection of elements having same data type.

Two-dimensional(2D)arrays are indexed by two subscripts, one for the row and one for the column.

JVM creates 5 * 5 = 25 blocks of memory. These blocks can be individually referred to as shown below

numbers[0][0]  numbers[0][1]  numbers[0][2]  numbers[0][3]  numbers[0][4]
numbers[1][0]  numbers[1][1]  numbers[1][2]  numbers[1][3]  numbers[1][4]
numbers[2][0]  numbers[2][1]  numbers[2][2]  numbers[2][3]  numbers[2][4]
numbers[3][0]  numbers[3][1]  numbers[3][2]  numbers[3][3]  numbers[3][4]
numbers[4][0]  numbers[4][1]  numbers[4][2]  numbers[4][3]  numbers[4][4]

Below program is use to display all the values in matrix.

package com.ms.matrix;

public class Matrix {

  public static void main(String[] args) {
    int numbers[][]={{23,45,57,24,74},{34,67,23,55,23},{34,74,24,46,78},
              {23, 56,87, 89,96}, {95, 03, 45, 99,56}};
      System.out.println("####################################################");
    
      printMatrix(numbers);
      
      System.out.println("####################################################");
   	
  }

  public static void printMatrix(int[][] numbers){
    for (int i = 0; i < numbers.length; i++)
      {
          for (int j = 0; j < numbers.length; j++)
          {
              System.out.print(numbers[i][j]+ "\t");
          }
          System.out.println();
      }
  }
}

If an array element does not exists, Java runtime system will give throw an “ArrayIndexOutOfBoundsException”.

Example:

int[][] reviews = new int[5][6];

What will be the value of reviews.length?
Answer: 5, the number of rows (first dimension)

What will be the value of reviews[0].length?
Answer: 6, the number of columns (second dimension)

Question:

Find number of reviews greater than value sent to method.

public int greaterReviews(int[][] reviews, int num) { 
  int count = 0; 
  for (int row = 0; row < reviews.length; row++) { 
    for (int col = 0; col < reviews[0].length; col++){
       if (reviews[row][col] > num){ 
        count++;
      } 
    }
  }
  return count;  
}
Let's Share
Show Buttons
Hide Buttons