DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Effective Java Collection Framework: Best Practices and Tips
  • JQueue: A Library to Implement the Outbox Pattern
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Java Concurrency: Understanding the ‘Volatile’ Keyword

Trending

  • Testing SingleStore's MCP Server
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  1. DZone
  2. Data Engineering
  3. Data
  4. What Is a Jagged Array in Java With Examples?

What Is a Jagged Array in Java With Examples?

The Arrays and Multi-dimensional Arrays are before we can learn about Jagged arrays. we want to store information about students and their respective grades.

By 
Mahesh Sharma user avatar
Mahesh Sharma
·
Jan. 22, 24 · Code Snippet
Likes (3)
Comment
Save
Tweet
Share
7.7K Views

Join the DZone community and get the full member experience.

Join For Free

Jagged Array in Java

A jagged array, also known as an array of arrays, is a data structure in which an array is used to store other arrays. The key characteristic of a jagged array is that each element of the main array can be of different sizes, allowing for variable column lengths in a two-dimensional structure.

To understand the concept of a Jagged array, let's consider an example. Suppose we want to store information about students and their respective grades. We can create a jagged array to represent this data structure. Here's how it would look:

jagged array

 

The benefit of using a jagged array is that it allows for flexibility in storing data when the number of elements in each subarray is different. This is particularly useful in scenarios where the number of columns may vary, such as when dealing with irregular data or sparse matrices.

Overall, jagged arrays provide a flexible way to represent and work with data structures where the size of each dimension can vary, making them a powerful tool in certain programming scenarios.

Example 1

In the above code, we first declare a 2D jagged array jagged Array with three rows. However, we do not specify the column lengths at this point. Next, we assign different-sized arrays to each row of the jagged array. The first row has three elements, the second has two elements, and the third has four elements. 

Finally, we use nested loops to iterate over the jaggedarray and print its elements. The outer loop iterates over the rows, and the inner loop iterates over the columns of each row.

FileName: JaggedArrayExample.java

Java
 
public class JaggedArrayExample {

    public static void main(String[] args) {

        int[][] jaggedArray = new int[3][];

        

        // Assigning different-sized arrays to the jagged array

        jaggedArray[0] = new int[] { 1, 2, 3, 4 };

        jaggedArray[1] = new int[] { 5, 6, 7 };

        jaggedArray[2] = new int[] { 8, 9 };

        

        // Accessing and printing the elements of the jagged array

        for (int i = 0; i < jaggedArray.length; i++) {

            for (int j = 0; j < jaggedArray[i].length; j++) {

                 System.out.print(jaggedArray[i][j] + " ");

            }

            System.out.println();

        }

    }

}


Output

 
1 2 3 4 

5 6 7 

8 9

 

Example 2

In the above code, we declare a 2D jagged array jaggedArray and initialize it with student names in different grades. The first row represents the names of students in the first grade. The second row represents the names of students in the second grade and so on. 

We then use nested loops to iterate over the jagged array and print the names of students in each grade. The outer loop iterates over the rows (grades), and the inner loop iterates over each grade’s columns (students).

FileName: JaggedArrayExample.java

Java
 
public class JaggedArrayExample {

     public static void main(String[] args) {

        // Declare and initialize a 2D jagged array to store names of students in different grades

        String[][] jaggedArray = {

            { "Ram", "Laxman" },                           // Grade 1 students

            { "Rahul", "Gauri", "Komal" },                // Grade 2 students

            { "Ajinkya", "Virat", "Tejaswi", "Sanju" }      // Grade 3 students

        };

        

        // Accessing and printing the elements of the jagged array

        for (int i = 0; i < jaggedArray.length; i++) {   // Iterate over the rows (grades)

            System.out.print("Grade " + (i + 1) + " students: ");

            for (int j = 0; j < jaggedArray[i].length; j++) {  // Iterate over the columns (students) of each grade

                 System.out.print(jaggedArray[i][j] + " ");    // Print the name of each student

            }

            System.out.println();   // Move to the next line after printing the names of students in a grade

        }

     }

}


Output

 
Grade 1 students: Ram Laxman 

Grade 2 students: Rahul Gauri Komal 

Grade 3 students: Ajinkya Virat Tejaswi Sanju


Example 3

In the above code, we have a jagged array jaggedArray that stores different numbers in each row. The first row has three elements, the second row has two elements, the third row has four elements, and the fourth row has one element. Then 

We use nested loops to iterate over the jagged array and calculate the sum of each row. The outer loop iterates over the rows, and the inner loop iterates over the columns of each row. The sum of each row is calculated by adding up all the elements in that row.

FileName: JaggedArrayExample.java

Java
 
public class JaggedArrayExample {

     public static void main(String[] args) {

        int[][] jaggedArray = {

            { 1, 2, 3 },      // First row with three elements

            { 4, 5 },         // Second row with two elements

            { 6, 7, 8, 9 },   // Third row with four elements

            { 10 }            // Fourth row with one element

        };

        

        // Calculate the sum of each row and display the results

        for (int i = 0; i < jaggedArray.length; i++) {

            int rowSum = 0;

            for (int j = 0; j < jaggedArray[i].length; j++) {

                rowSum += jaggedArray[i][j];

            }

            System.out.println("Sum of row " + (i + 1) + ": " + rowSum);

        }

     }

}


Output

 
Sum of row 1: 6

Sum of row 2: 9

Sum of row 3: 30

Sum of row 4: 10


Data structure Data (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Effective Java Collection Framework: Best Practices and Tips
  • JQueue: A Library to Implement the Outbox Pattern
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Java Concurrency: Understanding the ‘Volatile’ Keyword

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!