Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A jagged array in Java is an array of arrays where each element is itself an array, and the length of each inner array can vary. Unlike a multidimensional array, which has a fixed size for each dimension, a jagged array allows for different sizes of the inner arrays. This flexibility makes jagged arrays useful for representing and manipulating data structures with varying dimensions or uneven sizes. In this article, we will discuss this in detail like syntax, declaration, implementation, significance, etc.
What is Jagged Array In Java?
In Java, a jagged array is an array of arrays where each element of the outer array is an array itself, and the length of each inner array can be different. It is also known as an array of arrays or a ragged array. Unlike a multidimensional array, which has a fixed size for each dimension, a jagged array allows for varying sizes of the inner arrays.
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.
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.
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
Complexity of Jagged Array In Java
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:
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(); } } }
You can also try this code with Online Java Compiler
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:
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.
Jagged arrays perform better than the normal arrays. The performance increases as we have the chance to customize the column of the row.
Jagged arrays are efficient when we have irregularity in the data or are unsure about how many elements will be present in the array.
Visualization is easy in jagged arrays. Array visualization becomes easy in jagged arrays when dealing with the multidimensional array.
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));
}
}
}
You can also try this code with Online Java Compiler
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));
}
}
}
You can also try this code with Online Java Compiler
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.
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));
}
}
}
You can also try this code with Online Java Compiler
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 in Java
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
Why do we use a jagged array?
Jagged arrays are used to save memory and manage data where each row may have a different number of columns efficiently.
What is a jagged data structure?
A jagged data structure, such as a jagged array, consists of arrays of arrays, each inner array potentially having different lengths.
Is there a jagged array in C++?
Yes, C++ supports jagged arrays, which are arrays of pointers to arrays of potentially varying sizes, managed through dynamic memory allocation.
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.