Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Working with 2-D Array in Java

In this lesson, you will learn.

  • 2-D Array in Java
  • Jagged Array
  • Examples

 

2-D Array in Java

  • A 2-D array in Java, often referred to as a matrix or a table, is an array of arrays.
  • Each element of a 2-D array is itself an array.

This structure is particularly useful when you need to store tabular data, like a grid or a spreadsheet, where you have rows and columns.

 

Syntax of 2-D Array

The syntax for declaring a 2-D array in Java is similar to that of a one-dimensional array, but with an additional set of square brackets.

 

Declaration

dataType[][] arrayName;

Here, dataType can be any valid Java data type, and arrayName is the variable name for the array.

 

Instantiation

arrayName = new dataType[rows][columns];

This creates a 2-D array with the specified number of rows and columns.

 

Example

int twoD[][] = new int[3][3];

The below figure shows the memory representations of the 2-D Array

Initialization of 2-D Array

 

1. Static Initialization

Static initialization is when the size and elements of the array are known beforehand.

You can initialize a 2-D array inline while declaring it:

int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

 

2. Dynamic Initialization

Dynamic initialization is when the elements of the array are assigned values after declaration.

int[][] arr = new int[3][3]; // 3x3 array
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
// and so on for the rest of the elements...

 

Below is the conceptual view of elements of 2-D arrays.

 

3. Array of Arrays

Since a 2D array is an array of arrays, you can also initialize it by directly creating arrays for each of its elements.

int[][] arr = new int[3][];
arr[0] = new int[]{1, 2, 3};
arr[1] = new int[]{4, 5, 6};
arr[2] = new int[]{7, 8, 9};

 

Example 1: Displaying Elements of an Array

package ch6;

public class Basic2DArray {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output

1 2 3 
4 5 6 
7 8 9 

 

Example 2: Summing Elements of a 2-D Array

package ch6;

public class Sum2DArray {
    public static void main(String[] args) {
        int[][] numbers = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int sum = 0;
        for (int[] row : numbers) {
            for (int num : row) {
                sum += num;
            }
        }

        System.out.println("Sum of all elements: " + sum);
    }
}

Output

Sum of all elements: 45

 

Jagged Array

  • A Jagged Array in Java is an array of arrays in which the length of each array (row) can differ, meaning that each sub-array can have a different number of elements.
  • Jagged arrays are useful when you need a table-like structure but with variable row sizes.

 

Note: Memory allocation for a multidimensional array requires specifying the first dimension, allowing for the separate allocation of remaining dimensions, as demonstrated in the code.

 

Example

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

 

The below figure shows the conceptual view of a 2-D Jagged Array.

 

 

Example 1: Jagged Array

package twodarray;

public class JaggedArray {
    public static void main(String[] args) {
        int[][] jaggedArray = new int[3][];
        jaggedArray[0] = new int[2];
        jaggedArray[1] = new int[3];
        jaggedArray[2] = new int[1];

        // Initializing values
        int num = 1;
        for (int i = 0; i < jaggedArray.length; i++) {
            for (int j = 0; j < jaggedArray[i].length; j++) {
                jaggedArray[i][j] = num++;
            }
        }

        // Printing the jagged array
        for (int[] row : jaggedArray) {
            for (int value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

 

Output

1 2 
3 4 5 
6 

 

Example 2: Storing Different Days of Week Hours

package twodarray;

public class WeeklyHours {
    public static void main(String[] args) {
        // Creating a jagged array for hours 
    	// worked on different days of the week
        double[][] weekHours = {
            {8.5}, // Monday
            {8.0, 3.5}, // Tuesday (two shifts)
            {8.0}, // Wednesday
            {8.0, 4.0}, // Thursday (two shifts)
            {6.5}, // Friday
            {}, // Saturday (no work)
            {} // Sunday (no work)
        };

        // Displaying hours
        String[] days = {"Monday", "Tuesday", "Wednesday", 
        		"Thursday", "Friday", "Saturday", "Sunday"};
        for (int i = 0; i < weekHours.length; i++) {
            System.out.print(days[i] + ": ");
            for (double hours : weekHours[i]) {
                System.out.print(hours + " ");
            }
            System.out.println();
        }
    }
}

 

Output

Monday: 8.5 
Tuesday: 8.0 3.5 
Wednesday: 8.0 
Thursday: 8.0 4.0 
Friday: 6.5 
Saturday: 
Sunday: 

 

Example 3: Student Grades in Different Subjects

This example demonstrates a jagged array representing grades of students in different subjects, where each subject might have a different number of assessments.

package twodarray;

public class StudentGrades {
    public static void main(String[] args) {
        // Grades for three subjects, each having 
    	// a different number of assessments
        int[][] grades = {
            {87, 92}, // Grades in Subject 1 (e.g., Math)
            {78, 85, 90}, // Grades in Subject 2 (e.g., Science)
            {85, 80} // Grades in Subject 3 (e.g., History)
        };

        // Subject names
        String[] subjects = {"Math", "Science", "History"};

        // Displaying grades for each subject
        for (int i = 0; i < grades.length; i++) {
            System.out.print(subjects[i] + " Grades: ");
            for (int grade : grades[i]) {
                System.out.print(grade + " ");
            }
            System.out.println();
        }
    }
}

 

Output

Math Grades: 87 92 
Science Grades: 78 85 90 
History Grades: 85 80 

 

Exercise 1: Matrix Addition

Objective: Write a Java program that takes two 2D arrays (matrices) of the same dimensions as input and outputs their sum. Assume the size of both matrices is 3×3 for simplicity.

Sample Input:

Matrix 1:

1 2 3
4 5 6
7 8 9

Matrix 2:

9 8 7
6 5 4
3 2 1

Sample Output:

10 10 10
10 10 10
10 10 10

 

Exercise 2: Diagonal Sum

Objective: Create a Java program that calculates the sum of the elements on the diagonal of a square matrix. For an extra challenge, calculate both the primary and secondary diagonals.

Sample Input:

1 2 3
4 5 6
7 8 9

Sample Output:

Primary Diagonal Sum: 15
Secondary Diagonal Sum: 15

 

Exercise 3: Check the Symmetric Matrix

Objective: Write a Java method that checks if a given matrix is symmetric. A matrix is symmetric if it is equal to its transpose.

Sample Input:

1 2 3
2 4 5
3 5 6

Sample Output:

True

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review