Exploring Two-Dimensional Array in Java with Examples

Updated on July 29, 2024

Article Outline

In Java, a two-dimensional array is essentially an array of arrays. It allows you to store data in a grid-like format, where each element is accessed by specifying both row and column indices. This article will explore how two-dimensional arrays work in Java, how to initialize and manipulate them and provide examples to illustrate their usage.

Introduction to 2D Array in Java

A two-dimensional array in Java is an array of arrays. Java arrays allow storing data in contiguous memory, where each element is accessed using two indices: one for the row and another for the column. This structure is useful for representing grids, tables, matrices, and other data structures that require rows and columns.

Java Array

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

2D Array Declaration in Java

To declare a two-dimensional array in Java, You specify the data type of the elements followed by two sets of square brackets ‘[]’. For example,

// Declaration of a 2D array of integers int[][] matrix;

The above syntax only declares a dimensional array in Java; memory is allocated for the array object, but values will be added later.

Create Two Dimensional Array in Java

Everything, including the array data structure, in Java language is treated as objects. Hence, we must use the new keyword to create a two-dimensional array object, as shown below. Let’s describe it below:

// Declaring 2D array DataType[][] ArrayName; // Creating a 2D array ArrayName = new DataType[m][n];

This statement creates a two-dimensional array object that contains m rows and n columns of DataType type. This array object is referenced by the reference variable ArrayName.

Java Two-Dimensional Array of Primitive Type

Java arrays are a collection of elements that have similar data types. Hence, we can create an array of primitive data types and objects. A 2D array of a primitive data type in Java for example int, is simply an array of integer arrays. Let’s declare a 2D array in java for all the primitive Java data types in the following manner.

int[][] AIntegerArray; // 2D Integer Array byte[][] AByteArray; // 2D Byte Array short[][] AShortArray; // 2D Short Array long[][] ALongArray; // 2D Long Array float[][] AFloatArray; // 2D Float Array double[][] ADoubleArray; // 2D Double Array boolean[][] ABooleanArray; // 2D Boolean Array char[][] ACharArray; // 2D Character Array

Java Two-Dimensional Array of Objects

We can create an array of objects. A two-dimensional array of objects in Java is simply a collection of arrays of several reference variables.  We can declare a 2D array of objects in the following manner.

ClassName[][] arrName ;

The syntax declares a two-dimensional array with the name arrName that can store the object of class className in tabular form.

Accessing Two-Dimensional Array Elements in Java

Arrays are stored in contiguous memory locations, and numeric indexing references these memory locations. In Java, we can directly access any element from an array using indexing.

DataType[][] ArrayName = new DataType[m][n] ; // Accessing an element DataType arrayName = ArrayName[i][j];

Here, The arrayName[i][j] statement is used to access the element present at the intersection of i and j columns in the two-dimensional array ArrayName. This element will be stored in the arrayName variable.

Example of Java Two-Dimensional Array

Imagine you have data representing monthly temperatures over several years. You want to calculate the average temperature for each month. Let’s use a two-dimensional array to organize and process this data.

 

Problem Statement

Given monthly temperature data for multiple years.

 

  • Create a two -dimensional array to store temperatures.
  • Calculate the average temperature for each month across all years.

 

The following program solves this problem statement:

 

Program

class Main { public static void main(String[] args) { int[][] temperatures = { {25, 26, 27, 28, 30, 31, 32, 31, 30, 28, 27, 26}, {24, 25, 26, 27, 29, 30, 31, 30, 29, 27, 26, 25}, {23, 24, 25, 26, 28, 29, 30, 29, 28, 26, 25, 24} };  double[] averageTemperatures = new double[12];  for (int month = 0; month < 12; month++) { int sum = 0; for (int year = 0; year < temperatures.length; year++) { sum += temperatures[year][month]; } averageTemperatures[month] = (double) sum / temperatures.length; }  System.out.println("Average Monthly Temperatures:"); for (int month = 0; month < 12; month++) { System.out.printf("Month %d: %.2fn", month + 1, averageTemperatures[month]); } } }

Output

Average Monthly Temperatures: Month 1: 24.00 Month 2: 25.00 Month 3: 26.00 Month 4: 27.00 Month 5: 29.00 Month 6: 30.00 Month 7: 31.00 Month 8: 30.00 Month 9: 29.00 Month 10: 27.00 Month 11: 26.00 Month 12: 25.00

Ways to Declare and Initialize Two-Dimensional Array in Java

In the Java language, we can declare and initialize 2D arrays in various ways. Let’s look each way one by one.

 

1. Declaring the 2D array with both dimensions: We can declare a two-dimensional array using both dimensions. We have to pass the number of rows and the number of columns of the matrix in the square matrix.

int[][] arr = new int[22][5];

2. Declaring a two-dimensional array with just one dimension: The Java language treats a two-dimensional array as an array of arrays. This means we can declare a two-dimensional array using only one dimension, which is the number of rows, as the first dimension determines the number of array references.

int[][] arr = new int[22][];

This syntax declares a two-dimensional Integer array having two rows and an undefined number of columns. This array object arr refers to an array that can refer to two one-dimensional arrays in Java.

 

3. Position of the square bracket: When declaring a two-dimensional array, the position of the square brackets in the declaration statement is important. Incorrect positioning can lead to unexpected results. Let’s see some examples to understand the common mistakes related to the position of square brackets.

int m[], mb[][] ;

In the above syntax, we are declaring two array objects m and mb, where m represents a one-dimensional integer array and mb represents a two-dimensional integer array.

int [] a[] = new int[2] [2] ;

 

4. 2D Array with Variable Column Length: In Java, we can declare a two-dimensional array with a variable column length using the given syntax.

int arr[] = new int[5][] ; arr[0] = new int[30]; arr[1] = new int[25]; arr[2] = new int[38]; arr[3] = new int[40];<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;">          </strong>

Conclusion

In this article, we have explored the concept of two-dimensional arrays in Java, focusing on their declaration, initialization, and usage with various examples. Two-dimensional arrays are essential for handling data in a grid or matrix format, common in many real-world applications such as image processing, scientific computation, and database management. By understanding two-dimensional arrays, developers can implement it efficiently in the Java program.

FAQs
A two-dimensional array in Java is an array array, forming a grid or matrix of elements. Each element in the array can be accessed using two indices. One for the row and one for the column.
We can initialize a two-dimensional array at the time of declaration or separately using the ‘new’ keyword. For example   int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Or int[][] matrix = new int[3][3];
We can initialize a two-dimensional array at the time of declaration or separately use the ‘new’ keyword.   int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Or int[][] matrix = new int[3][3];
Elements in a two-dimensional array are accessed using row and column indices.   int value = matrix[rowIndex][columnIndex];  
We can use nested loops to iterate over all elements.   for(int i = 0 ;i<matrix.length ;i++){ for (int j = 0; j < matrix[i].length; j++) { System.out.println(matrix[i][j]); } }

Updated on July 29, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved