Open In App

Jagged Array in Java

Last Updated : 05 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Arrays in Java

A jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These types of arrays are also known as Jagged arrays. 

Pictorial representation of Jagged array in Memory:

Jagged_array

 

Declaration and Initialization of Jagged array :

Syntax: data_type array_name[][] = new data_type[n][];  //n: no. of rows
             array_name[] = new data_type[n1] //n1= no. of columns in row-1
             array_name[] = new data_type[n2] //n2= no. of columns in row-2
             array_name[] = new data_type[n3] //n3= no. of columns in row-3
                                   .
                                   .
                                   .
             array_name[] = new data_type[nk]  //nk=no. of columns in row-n

 

Alternative, ways to Initialize a Jagged array :

                    int arr_name[][] = new int[][]  {
                                  new int[] {10, 20, 30 ,40},
                                  new int[] {50, 60, 70, 80, 90, 100},
                                  new int[] {110, 120}
                                      };
                                      
                              OR                                     
                                                         
                    int[][] arr_name = {
                          new int[] {10, 20, 30 ,40},
                          new int[] {50, 60, 70, 80, 90, 100},
                          new int[] {110, 120}
                              };
                              
                              OR                                     
                                                         
                    int[][] arr_name = {
                           {10, 20, 30 ,40},
                           {50, 60, 70, 80, 90, 100},
                           {110, 120}
                              };

Following are Java programs to demonstrate the above concept. 

Java




// Program to demonstrate 2-D jagged array in Java
class Main {
    public static void main(String[] args)
    {
        // Declaring 2-D array with 2 rows
        int arr[][] = new int[2][];
 
        // Making the above array Jagged
 
        // First row has 3 columns
        arr[0] = new int[3];
 
        // Second row has 2 columns
        arr[1] = new int[2];
 
        // Initializing array
        int count = 0;
        for (int i = 0; i < arr.length; i++)
            for (int j = 0; j < arr[i].length; j++)
                arr[i][j] = count++;
 
        // Displaying the values of 2D Jagged array
        System.out.println("Contents of 2D Jagged Array");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}


Output

Contents of 2D Jagged Array
0 1 2 
3 4 

Following is another example where i’th row has i columns, i.e., the first row has 1 element, the second row has two elements and so on.

Java




// Another Java program to demonstrate 2-D jagged
// array such that first row has 1 element, second
// row has two elements and so on.
class Main {
    public static void main(String[] args)
    {
        int r = 5;
 
        // Declaring 2-D array with 5 rows
        int arr[][] = new int[r][];
 
        // Creating a 2D array such that first row
        // has 1 element, second row has two
        // elements and so on.
        for (int i = 0; i < arr.length; i++)
            arr[i] = new int[i + 1];
 
        // Initializing array
        int count = 0;
        for (int i = 0; i < arr.length; i++)
            for (int j = 0; j < arr[i].length; j++)
                arr[i][j] = count++;
 
        // Displaying the values of 2D Jagged array
        System.out.println("Contents of 2D Jagged Array");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}


Output

Contents of 2D Jagged Array
0 
1 2 
3 4 5 
6 7 8 9 
10 11 12 13 14 

Example 

Java




import java.util.Scanner;
 
public class JaggedArray {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number of sub-arrays: ");
        int numberOfArrays = scan.nextInt();
         
        // Declare the jagged array
        int[][] jaggedArray = new int[numberOfArrays][];
         
        // Allocate memory to each sub-array
        for (int i = 0; i < numberOfArrays; i++) {
            System.out.print("Enter the size of sub-array " + (i + 1) + ": ");
            int sizeOfSubArray = scan.nextInt();
            jaggedArray[i] = new int[sizeOfSubArray];
        }
         
        // Initialize the elements of each sub-array
        for (int i = 0; i < numberOfArrays; i++) {
            System.out.println("Enter the elements of sub-array " + (i + 1) + ":");
            for (int j = 0; j < jaggedArray[i].length; j++) {
                jaggedArray[i][j] = scan.nextInt();
            }
        }
         
        // Print the elements of the jagged array
        System.out.println("The jagged array is:");
        for (int i = 0; i < numberOfArrays; i++) {
            for (int j = 0; j < jaggedArray[i].length; j++) {
                System.out.print(jaggedArray[i][j] + " ");
            }
            System.out.println();
        }
         
        scan.close();
    }
}


 

Jagged arrays have the following advantages in Java:

  • Dynamic allocation: Jagged arrays allow you to allocate memory dynamically, meaning that you can specify the size of each sub-array at runtime, rather than at compile-time.
  • Space utilization: Jagged arrays can save memory when the size of each sub-array is not equal. In a rectangular array, all sub-arrays must have the same size, even if some of them have unused elements. With a jagged array, you can allocate just the amount of memory that you need for each sub-array.
  • Flexibility: Jagged arrays can be useful when you need to store arrays of different lengths or when the number of elements in each sub-array is not known in advance.
  • Improved performance: Jagged arrays can be faster than rectangular arrays for certain operations, such as accessing elements or iterating over sub-arrays, because the memory layout is more compact.

It’s important to note that jagged arrays also have some disadvantages, such as increased complexity in the code and a potentially less readable codebase, so they should be used carefully and appropriately.

 

 



Previous Article
Next Article

Similar Reads

Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
How to Convert java.sql.Date to java.util.Date in Java?
If we have the Date object of the SQL package, then we can easily convert it into an util Date object. We need to pass the getTime() method while creating the util Date object. java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); It will give us util Date object. getTime() method Syntax: public long getTime() Parameters: The function do
1 min read
Different Ways to Convert java.util.Date to java.time.LocalDate in Java
Prior to Java 8 for handling time and dates we had Date, Calendar, TimeStamp (java.util) but there were several performance issues as well as some methods and classes were deprecated, so Java 8 introduced some new concepts Date and Time APIs' (also known as Joda time APIs') present in java.time package. Java 7: Date, Calendar, TimeStamp present ins
3 min read
How to Convert java.util.Date to java.sql.Date in Java?
Date class is present in both java.util package and java.sql package. Though the name of the class is the same for both packages, their utilities are different. Date class of java.util package is required when data is required in a java application to do any computation or for other various things, while Date class of java.sql package is used whene
3 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Sort an Array and Insert an Element Inside Array in Java
Sorting an array can be done by using inbuilt sort function while for the insertion we have to create a new array to do so as arrays in Java are immutable. To learn more about sorting in Java follow the article mentioned below: Sorting: Arrays.sort() in Java with examples Approach 1: Create a new array of size N+1.Copy first array in New array.Inse
3 min read
Java Program to Check Array Bounds while Inputting Elements into the Array
Concept: Arrays are static data structures and do not grow automatically with an increasing number of elements. With arrays, it is important to specify the array size at the time of the declaration. In Java, when we try to access an array index beyond the range of the array it throws an ArrayIndexOutOfBounds Exception. An exception is an obstructio
4 min read
Remove One Array From Another Array in Java
For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter. Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be re
3 min read
How to Convert JSON Array to String Array in Java?
JSON stands for JavaScript Object Notation. It is one of the widely used formats to exchange data by web applications. JSON arrays are almost the same as arrays in JavaScript. They can be understood as a collection of data (strings, numbers, booleans) in an indexed manner. Given a JSON array, we will discuss how to convert it into a String array in
3 min read
Java Program to Modify given array to a non-decreasing array by rotation
Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation: After 2 right rotations, the array arr[] modifies to {1,
2 min read
Practice Tags :