Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Jagged Array In Java?
2.1.
Jagged Array Example
3.
Declaration and Initialization of Jagged array
3.1.
Implementation in Jagged array in Java
3.2.
Input
3.3.
Output
3.4.
Complexity
3.4.1.
Time complexity
3.4.2.
Space Complexity
4.
Pictorial Representation of Jagged Array in Memory
5.
Read and Store Elements in a Dynamic Sized Jagged Array
5.1.
Java
6.
Significance of Jagged Arrays
7.
Ways to Initialize a Jagged Array:
7.1.
1. Using Java 8 streams:
7.2.
2. Dynamic jagged array:
7.3.
Using array literals:
7.4.
Using nested loops:
8.
Advantages of Jagged Array
9.
Frequently Asked Questions
9.1.
What situations call for a jagged array in Java?  
9.2.
What is the use of a Jagged array?
9.3.
Are jagged arrays faster?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Jagged array in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Hello Ninja, Welcome back. One of the easiest topics is Array. This tutorial explains the Jagged Array in java and Multidimensional Array. We will discover how to build, set it up, and deploy jagged arrays.

An array with only other arrays as its elements is said to be jagged. Read the article Arrays in Java if you are not familiar with the basics of an array before continuing. 

jagged array in java

What is Jagged Array In Java?

It is an array of arrays in Java, where each element is an array in turn. This type of multidimensional array has the unique property that each element can have a varied size.

Jagged Array Example

An array of single-dimensional arrays makes up a two-dimensional Array in Java. A two-dimensional array will contain one set of columns for each one-dimensional array.

A Jagged array in Java is seen in the image below.

Jagged Array Example

The above drawing gave us a broad idea of how it appears. The image above shows a two-dimensional Jagged array in Java. As seen above, each component of this array is a one-dimensional array with various sizes.

We can see in the above example that the first dimension has four columns, the second has six columns, the third has two columns, and the fourth has six columns.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Declaration and Initialization of Jagged array

When generating an array of arrays, you need to supply the first dimension, which stands for the number of rows in the array, when generating an array of arrays.

A two-dimensional jagged array in Java can be made as follows:

int Jagged_array [ ] [ ] = new int[ 4 ][ ] ;

Four rows are declared.

You may define an array as a jagged array in Java after it has been declared, as demonstrated below:

Jagged_array [ 1 ] = new int [ 4 ] ;
Jagged_array [ 2 ] = new int [ 6 ] ;
Jagged_array [ 3 ] = new int [ 2 ] ;
Jagged_array [ 4 ] = new int [ 6 ] ;

The array can be initialized with values after it has been constructed.

Implementation in Jagged array in Java

// Program for jagged array in Java
import java.util.*;
import java.io.*;

public class Main {

  public static void main(String[] args) {
      Scanner inpur_object=new Scanner(System.in);
      
      // User's input
      int r = imput_object.nextInt();
 
        // declaring an r-row jagged array in java
        int jagged_arr[][] = new int[r][];
 
        /* We are building a jagged array in java with the 0th row having one element, the 1st row having two, and the nth row having n+1 items.
        */
        for (int i = 0; i < jagged_arr.length; i++)
            jagged_arr[i] = new int[i + 1];
 
        // Array initialization
        int temp = 0;
        for (int i = 0; i < jagged_arr.length; i++)
            for (int j = 0; j < jagged_arr[i].length; j++)
                jagged_arr[i][j] = temp++;
 
        // showing the 2-D Jagged array's components
        System.out.println("Elements of 2-D Jagged Array for n= " + r);
        for (int i = 0; i < jagged_arr.length; i++) {
            for (int j = 0; j < jagged_arr[i].length; j++)
                System.out.print(jagged_arr[i][j] + " ");
            System.out.println();
        }
  }
}

Input

9

Output

output

Practice it on online java compiler.

Complexity

Time complexity

O(N*M): The complexity of the above program is O(N*M). Where N is the row of the jagged array in Java.

Reason: The time complexity is O(N*M) because it is traversing from 0 to N in the first for loop, and in the same nested loop, it is traversing from 0 to M.

Space Complexity

O(N*M): The complexity of the above program is O(N*M). Where N is the row of the jagged array in Java.

Reason: In the worst situation, every row can have an M number of the column, so the space complexity will be O(N*M). 

Pictorial Representation of Jagged Array in Memory

A jagged array is an array such that the subarrays can be of different sizes. The pictorial representation of the jagged array is shown below:

pictorial representation of jagged array

The above representation is the presentation of a jagged array. So, this array has four rows, and each row has a different number of columns. This gets stored in th heap section of the memory and each section of the jagged array is a one-dimensional array. 

Read and Store Elements in a Dynamic Sized Jagged Array

In the code below, we are taking input from the user to enter the row count, and we store that value in our variable rows. Next we initialize our jagged arrays with that row value. In the next, we ask the user to enter the subarray size for row 1. Later, using the for loop, we take input for that subarray from the user. It continues till we reach the end of the row count. In last, we print the jagged array using for loop.  

  • Java

Java

import java.util.Scanner;
public class CodingNinjas{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter row count: ");
int rows = sc.nextInt();

int[][] arr = new int[rows][];


for (int i = 0; i < rows; i++) {
System.out.print("Enter the number of elements in row " + (i + 1) + ": ");
int elements = sc.nextInt();
arr[i] = new int[elements];
System.out.println("Enter the elements for row " + (i + 1));
for (int j = 0; j < elements; j++) {
arr[i][j] = sc.nextInt();
}
}

System.out.println("Elements in 2-D Jagged Array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}

Output

Output

Significance of Jagged Arrays

Jagged arrays have several use cases and advantages. It is widely used in programming as it helps in various ways. Some of them are listed below:

  1. Jagged arrays are memory efficient. Memory gets allocated only to the elements present in the array. Memory space is utilized only for the members present in the array, which is better than the rectangular array. Wastage of memory is reduced.
     
  2. Jagged arrays perform better than the normal arrays. The performance increases as we have the chance to customize the column of the row. 
     
  3. Jagged arrays are efficient when we have irregularity in the data or are unsure about how many elements will be present in the array. 
     
  4. Visualization is easy in jagged arrays. Array visualization becomes easy in jagged arrays when dealing with the multidimensional array. 
     
  5. Dynamic resizing of subarrays helps in saving the structure of the data. Data updation, removal, or creation does not affect the structure of the array. 

 

Ways to Initialize a Jagged Array:

1. Using Java 8 streams:

import java.util.Arrays;
import java.util.stream.IntStream;
public class JaggedArrayInitialization {
   public static void main(String[] args) {
       int[][] jaggedArray = {
           IntStream.range(1, 4).toArray(),
           IntStream.range(5, 7).toArray(),
           IntStream.range(10, 11).toArray()
       };
       
       // Print jaggedArray
       for (int[] row : jaggedArray) {
           System.out.println(Arrays.toString(row));
       }
   }
}

 

Output:
 

output

In this example, we initialized a jagged array using Java 8 streams. The IntStream.range method was used to generate sequences of integers for each row, and the resulting arrays were assigned to the jagged array.

2. Dynamic jagged array:

import java.util.Arrays;
public class JaggedArrayInitialization {
   public static void main(String[] args) {
       int[][] jaggedArray = new int[3][];
       jaggedArray[0] = new int[] { 1, 2 };
       jaggedArray[1] = new int[] { 4, 5, 6 };
       jaggedArray[2] = new int[] { 7, 8, 9, 10 };
       
       // Print jaggedArray
       for (int[] row : jaggedArray) {
           System.out.println(Arrays.toString(row));
       }
   }
}

 

Output:

output

Here, the outer array is declared with a fixed size, and then inner arrays of varying lengths are created and assigned to each row based on specific values.

Using array literals:

import java.util.Arrays;

public class JaggedArrayInitialization {
    public static void main(String[] args) {
        int[][] jaggedArray = {
            { 1, 3 },
            { 4, 5, 6, 101 },
            { 7, 8, 9, 10 }
        };
        
        // Print jaggedArray
        for (int[] row : jaggedArray) {
            System.out.println(Arrays.toString(row));
        }
    }
}

 

Output:

output

Here, a jagged array is initialized using array literals. Each row is represented as a sub-array within the outer array, and the array elements are directly provided using curly braces.

Using nested loops:

import java.util.Arrays;

public class JaggedArrayInitialization {
    public static void main(String[] args) {
        int[][] jaggedArray = new int[3][];
        
        int value = 1;
        for (int i = 0; i < jaggedArray.length; i++) {
            jaggedArray[i] = new int[i + 1]; // Varying inner array lengths
            for (int j = 0; j < jaggedArray[i].length; j++) {
                jaggedArray[i][j] = value++;
            }
        }
        
        // Print jaggedArray
        for (int[] row : jaggedArray) {
            System.out.println(Arrays.toString(row));
        }
    }
}

 

Output:

output

In this example, nested loops are used to initialize a jagged array with varying inner array lengths. The length of each inner array increases with the row index, resulting in a jagged structure.

Advantages of Jagged Array

The following are some key advantages of using a Jagged Array in Java:-

  • Memory Efficiency: Jagged arrays are memory-efficient when you have arrays with varying lengths. Unlike rectangular arrays, jagged arrays only allocate memory for the actual elements in each inner array, which can lead to reduced memory consumption.
     
  • Irregular Data Structures: Jagged arrays are well-suited for representing irregular or ragged data structures, where each row may represent a different entity or have different attributes. This flexibility is useful for situations where different categories of data have different characteristics.
     
  • Simplicity in Creation: Creating a jagged array involves creating arrays for each row separately, which can be simpler when the sizes of the sub-arrays are not uniform.
     
  • Reduced Initialization Overhead: With jagged arrays, you only need to allocate memory for the elements you intend to use. This can reduce the overhead associated with initializing unused elements.
     
  • Dynamic Resizing: Jagged arrays can be resized more easily than rectangular arrays, as you can adjust the length of individual sub-arrays without affecting the entire structure.

Frequently Asked Questions

What situations call for a jagged array in Java?  

When working with multidimensional arrays, the efficiency can be improved by storing rows of data with different lengths in the jagged arrays, a specific array. A sequential collection of elements of the same data type may be called an array.

What is the use of a Jagged array?

A jagged array in Java, often referred to as a ragged array, is a collection of arrays whose members may have varying lengths, resulting in rows of jagged edges when seen as output. They are used when we don't want the 1-D array to be of the same length.

Are jagged arrays faster?

In most cases, the performance difference between using jagged arrays and rectangular arrays (with equal row lengths) might not be significant, especially for small to moderate-sized arrays. The choice between them should be based on the data structure you are trying to represent and the trade-offs between memory efficiency, ease of use, and minor performance differences.

Conclusion

We talked about jagged arrays in Java in this tutorial, which are multidimensional arrays with different-sized columns in each row. The system's performance can be enhanced by using these arrays.
The declaration itself or loops can be used to initialize them. An array of arrays and ragged arrays are other names for these arrays.

Check out the following problems - 


Please refer to our guided pathways on Code studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

If you find any problems, please comment. We will love to answer your questions.

Attempt our Online Mock Test Series on Coding Ninjas Studio now!

Ninja, have a great time learning.

Previous article
util.Arrays vs reflect.Array
Next article
How to Create Array of Objects in Java?
Live masterclass