Monday, 16 May 2022

Jagged arrays in Java

Java support jagged arrays. A Jagged array is an array whose elements are arrays with different dimensions.

 

 


There are two ways to define a Jagged arrays.

a.   Specify the jagged array size using array declaration

b.   Define the array, let Java deduce the size

 

 

Specify the jagged array size using array declaration

 

Example

int arr[][] = new int[3][];

arr[0] = new int[2];

arr[1] = new int[3];

arr[2] = new int[5];

 

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2

b.   arr[1] of size 3

c.    arr[2] of size 4.

 

Find the below working application.

 

JaggedArray1.java

package com.sample.app;

public class JaggedArray1 {

	public static void main(String[] args) {
		int arr[][] = new int[3][];
		arr[0] = new int[2];
		arr[1] = new int[3];
		arr[2] = new int[5];

		// Define array elements
		int count = 1;
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				arr[i][j] = count++;
			}
		}

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
			}
			System.out.println();
		}

	}

}

Output

arr[0][0] = 1
arr[0][1] = 2

arr[1][0] = 3
arr[1][1] = 4
arr[1][2] = 5

arr[2][0] = 6
arr[2][1] = 7
arr[2][2] = 8
arr[2][3] = 9
arr[2][4] = 10

Define the array elements, let Java deduce the size

Example

int arr[][] = {

                  { 1, 2 },

                  { 3, 4, 5},

                  { 6, 7, 8, 9, 10}

         };

Above snippet define a two-dimensional array, where

a.   arr[0] of size 2, and hold the elements {1, 2}

b.   arr[1] of size 3, and hold the elements {3, 4, 5}

c.    arr[2] of size 4. , and hold the elements {6, 7, 8, 9, 10}

 

Find the below working application.

 

JaggedArray2.java


package com.sample.app;

public class JaggedArray2 {

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

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				System.out.printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
			}
			System.out.println();
		}

	}

}

Output

arr[0][0] = 1
arr[0][1] = 2

arr[1][0] = 3
arr[1][1] = 4
arr[1][2] = 5

arr[2][0] = 6
arr[2][1] = 7
arr[2][2] = 8
arr[2][3] = 9
arr[2][4] = 10


You may like

Interview Questions

Call the main method of one class from other class using reflection

Java: Check whether a class exists in the classpath or not

How to get the name of calling class that invoke given method?

Implement map using array as storage

How to resolve NoClassDefFoundError?

No comments:

Post a Comment