Two Dimensional Array in Java Example Code

Overview

An Array is a special fixed-length container that holds a collection of values having a common data type. A two-dimensional array is an array of arrays i.e., it's a collection of arrays in which elements are arranged in rows and columns (tabular format).

Scope of the Article

  • This article provides an overview of two-dimensional arrays in Java.
  • The article covers all the theoretical aspects related to 2D array in Java along with their implementation in the Java programming language.
  • The overall article meets the desired scope.

Introduction to 2D Array in Java

Data represented in tabular form (organized in rows and columns) is a very effective means for communicating many different types of information. For example, we use tables to represent our expenditure or daily schedule, etc. In short, we generally use a rectangular grid (a collection of rows and columns) to organize the data.

In Java, this tabular representation of data is implemented using a two-dimensional array. A two-dimensional array (or 2D array in Java) is a linear data structure that is used to store data in tabular format.

Java 2D Array

In Java, an array is a homogeneous collection of a fixed number of values that are stored in contiguous memory locations i.e., the elements are of the same type (homogeneous data) and are linearly placed in memory such that each element is connected to its previous and the next element.

Java treats the two-dimensional array as an array of multiple one-dimensional arrays i.e., it is a collection of various one-dimensional arrays. Hence, when we create a 2D array object, Java creates a simple one-dimensional array that references (points to) other one-dimensional arrays which form the rows of the 2D array.

JVM Implementation of 2D Arrays

Hence, in Java, a two-dimensional array is a collection of pointers, where each pointer refers to a one-dimensional array that represents a particular row of the 2D array.

Two Dimensional Array Declaration in Java

Since a 2D array consists of rows and columns, we need two indices, one to refer rows and the other to a particular column in that row. Hence, the syntax of declaring a two-dimensional array is similar to that of a one-dimensional array with the exception of having two square brackets instead of one:

          

Here, the DataType describes the type of values that the array can store, while the ArrayName is the reference variable for the two-dimensional array object.

The above-described syntax only declares the array i.e., the memory is allocated for the array object but the values will be added later.

Create Two Dimensional Array in Java

In Java, everything including the array data structure is treated as objects. Hence, to create a two-dimensional array object we need to use the new keyword as shown below:

            
                                  // Declaring 2D array                                    DataType[][] ArrayName;                                                       // Creating a 2D array                                                      ArrayName =                                    new                                      DataType[r][c];                                                

Here, the new DataType[r][c] statement creates a two dimensional array object that contains r rows and c columns and elements of DataType type. This array object is referenced by the reference variable ArrayName.

Let's understand the creation of Java's two-dimensional array with an example:

            
                                  //Declaring 2D array                                                                        int                  [][] a;                                                      //Creating a 2D array                                                      a =                                    new                                                      int                  [                  3                  ][                  3                  ];                                                

Here, the reference variable a points to a two-dimensional array object that represents a 3 x 3 3x3 integer matrix i . e . i.e. , the array object contains 3 3 rows and 3 3 columns, and can only store integer (int) values.

Note: When we create a 2D array object using the new keyword, the JVM (Java Virtual Machine) allocates the memory required for the two-dimensional array and initializes the memory spaces with the default values according to the data type of the array object. For example, in the case of the Integer array (int[][]), every element of the array is initialized with the default value of 0.

Java Two Dimensional Array of Primitive Type

Arrays are a collection of elements that have similar data types. Hence, we can create an array of primitive data types as well as objects. A 2D array of a primitive data type in Java (let's say int) is simply an array of Integer arrays.

We can 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

As discussed earlier, 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:

          

This syntax declares a two-dimensional array having the name ArrayName that can store the objects of class ClassName in tabular form. These types of arrays that store objects as their elements are typically used while dealing with String data objects.

Access Two Dimensional Array Elements in Java

Arrays are stored in contiguous memory locations and use numeric indexing to reference these memory locations. Hence, we can directly access any element from an array using indexing. In the case of two-dimensional arrays, we use row and column indices to access a particular element from the matrix. It has the following syntax:

            
                                  // Creating a 2D Array                                                      DataType[][] ArrayName =                                    new                                      DataType[r][c]                                                      // Accessing an element                                                      DataType                                    var                                      = ArrayName[i][j];                                                

Here, the ArrayName[i][j] statement is used to access the element present at the intersection of i th row and j th column in the two dimensional array ArrayName. This element is then stored in the variable var.

Note :

  • In Java, the index always starts from 0. Hence to access the element in n th row, we need to use (n-1) as the index.
  • We can only access the elements of an array using positive integer as the index. We can't use negative indices to access any elements from an array in Java.
  • If we pass an index that is greater than the size of the array (out of bounds index), the ArrayIndexOutOfBoundsException error will occur.

Example of Java Two Dimensional Array

Now, let's look at an example to completely understand 2D arrays in Java.

Consider a scenario where we wish to store the marks attained by 3 students in Maths, English, and Science Subjects. Here, we are storing a collection of marks (marks of English, Maths, and Science) for each student. Hence, we can use a table to represent and store student marks. In the Student Marks table, the rows will represent the marks of a particular student and the columns will represent the subject in which the student attained those marks as shown below:

Java Two Dimensional Array Example

This Student Marks table can be mapped into Java using 2D arrays. We can use a two-dimensional integer array to represent the tabular form for the marks of students. This can be implemented in the following manner:

Code:

            
                                  import                                      java.util.Arrays;                                                      public                                                      class                                                      Main                                                      {                                                                        public                                                      static                                                      void                                                      main                  (String args[])                                                      {                                                                        int                  [][] StudentMarks =                                    new                                                      int                  [                  3                  ][                  3                  ];                                                                        // Marks Attained By Student 1                                                                          StudentMarks[                  0                  ][                  0                  ] =                                    90                  ;                                    // English                                                                          StudentMarks[                  0                  ][                  1                  ] =                                    70                  ;                                    // Maths                                                                          StudentMarks[                  0                  ][                  2                  ] =                                    84                  ;                                    // Science                                                                                          // Marks Attained By Student 2                                                                          StudentMarks[                  1                  ][                  0                  ] =                                    75                  ;                                    // English                                                                          StudentMarks[                  1                  ][                  1                  ] =                                    77                  ;                                    // Maths                                                                          StudentMarks[                  1                  ][                  2                  ] =                                    89                  ;                                    // Science                                                                                          // Marks Attained By Student 3                                                                          StudentMarks[                  2                  ][                  0                  ] =                                    69                  ;                                    // English                                                                          StudentMarks[                  2                  ][                  1                  ] =                                    93                  ;                                    // Maths                                                                          StudentMarks[                  2                  ][                  2                  ] =                                    83                  ;                                    // Science                                                                                          // Displaying Marks of Students                                                                          System.out.println(                  "Student Marks Matrix"                  );                                    System.out.println(Arrays.deepToString(StudentMarks));                                                  }                   }                              

Output:

            
                                  Student Marks Matrix                                    [[                  90                  ,                                    70                  ,                                    84                  ], [                  75                  ,                                    77                  ,                                    89                  ], [                  69                  ,                                    93                  ,                                    83                  ]]                                                

Here, we are declaring an Integer array StudentMarks that represents a 3x3 matrix. Now, to assign the marks of each student, we are accessing the corresponding elements using indexing and then assigning the marks to that particular element.

For example, to store the marks attained by student 1 in English, we are accessing the 0 th row (First student) and the 0 th column (First subject i.e., English) and then replacing the default integer value of 0 with the marks of the student (StudentMarks[0][0] = 90).

Finally, we are using the built-in method deepToString() of the Arrays class to display the student marks two-dimensional array.

Ways to Declare and Initialize Two Dimensional Array in Java

We can initialize and declare 2D arrays in various ways in Java. Let's look at each of these initialization methods in detail:

1. Declaring the 2D array with both dimensions

To declare a two-dimensional array using both dimensions, we just have to pass the number of rows and the number of columns of the matrix in the square brackets as shown below:

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

This syntax will declare a 2D Integer array having two rows and two columns.

2. Declaring a two-dimensional array with just one dimension

Since Java treats two-dimensional arrays as an array of arrays, 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                  [][] a =                                    new                                                      int                  [                  2                  ][];                                                

This syntax will declare a two-dimensional Integer array having two rows and an undefined number of columns i.e., the array object a refers to an array that can further refer to two one-dimensional arrays.

3. Position of the square bracket

When declaring a two-dimensional array, the position of the square bracket in the declaration statement can cause unexpected results. Let's look at some examples to understand the common mistakes related to the position of square brackets:

          

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

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

This syntax can be used to create two-dimensional arrays in Java as the int[] indicates a one-dimensional Integer array and the a[] is an array object itself, thereby declaring an integer array of arrays which is, in turn, a two-dimensional array.

4. 2D array with the variable column length

Since Java allows us to declare 2D arrays by providing only one dimension, we can declare a two dimensional array with variable column length using the syntax given below:

            
                                  int                                      a =                                    new                                                      int                  [                  4                  ][];                                    a[                  0                  ] =                                    new                                                      int                  [                  1                  ];                                    a[                  1                  ] =                                    new                                                      int                  [                  2                  ];                                    a[                  2                  ] =                                    new                                                      int                  [                  3                  ];                                    a[                  3                  ] =                                    new                                                      int                  [                  4                  ];                                                

The above syntax is declaring a two-dimensional integer array having 4 rows and the next four statements assign four one dimensional arrays having lengths 1, 2, 3, and 4 respectively as the rows of the array. The output of this two-dimensional array is shown below:

            
                                  [ [                  0                  ],                                                        [                  0                  ,                                    0                  ],                                                        [                  0                  ,                                    0                  ,                                    0                  ],                                                        [                  0                  ,                                    0                  ,                                    0                  ,                                    0                  ] ]                                                

These two-dimensional arrays having variable column lengths are typically used to represent a symmetric matrix which is a square matrix that contains duplicate elements alongside the main diagonal.

5. Declaring and initializing a heterogeneous 2D array

Since we can create a two-dimensional array of Objects, we can make use of this feature and Java's built-in Object class to create a two-dimensional heterogeneous array using the below-described syntax:

            
                                  Object[][] a =                                    new                                      Object[                  3                  ][];                                    a[                  0                  ] =                                    new                                      Integer[]{                  100                  ,                                    200                  ,                                    300                  };                                    a[                  1                  ] =                                    new                                      Character[]{                  'A'                  ,                                    'B'                  ,                                    'C'                  };                                    a[                  2                  ] =                                    new                                      Double[]{                  100.0                  ,                                    200.0                  };                                                

This syntax is declaring a two-dimensional array having 3 rows and variable-length columns. The above syntax creates a two-dimensional array that looks like this:

            
                                  [ [                  100                  ,                                    200                  ,                                    300                  ],                                    [A, B, C],                                      [                  100.0                  ,                                    200.0                  ] ]                                                

Here, note that we are not using the primitive data types like int, double, and char to declare the one-dimensional arrays. Instead, we are using their wrapper classes Integer, Character, and Double. This is because the two-dimensional array can only contain similar data type elements which in this case are objects of the built-in class Object.

Conclusion

  • In this article, we have seen the 2D arrays in Java and their uses.
  • Then we have seen various ways in which the two-dimensional arrays can be declared in Java.
  • We have also seen how Java treats the two-dimensional arrays and how the memory is allocated by the JVM to implement the two-dimensional arrays.
  • We have also noticed that we can use indexing to access and change the elements of the two-dimensional arrays.
  • Finally, we have seen the various ways in which the two-dimensional arrays can be initialized and declared in Java along with some common mistakes in declaration statements.

gadsonhavize.blogspot.com

Source: https://www.scaler.com/topics/two-dimensional-array-in-java/

0 Response to "Two Dimensional Array in Java Example Code"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel