What is Jagged Array In Java

A array which has got different number of elements in each row is calle as “Jagged “ Array. It is similar to normal 2D array but the only diference is number of elements in each row

Example for Normal Array

int[][] array1= {{1,2,3},{5,3,7},{7,5,4}}

Here we can see array1 is an example for Normal array as each row contains same number of elements or coloumns

first row contains 3 elements

second row constains 3 elements

third row contains 3 elements

Overall we say it’s a normal 2D array as all rows contain same number of elements

JAVA Code for NORMAL Array

package arrayproblems;

class Problem24 {

	public static void main(String[] args) {
		 
		int[][] array2= {{1,2},{3,4}}; // normal 2D array 
		
        // iterating through elements of array 
		
		for(int i=0;i<array2.length;i++) {
			
			for(int j=0;j<array2.length;j++) {
				
				System.out.print(array2[i][j]+" ");
			}
			System.out.println();
		}

	}

}

In above code we can observe that the array2 contains 2 row’s, each row contains 2 elements. so we are using two for loops to iterate through elements of array

Example for Jagged Array

int[][] array2={{1,2},{2,3,4},{5,7,3,2,1}}

In array2 we can see that first row contains only 2 elements ,

second row contains 3 elements

third row constains 5 elements

Overall we can observe that each row is having diferent number of elements or coloumns so it is an example for “Jagged array”.

JAVA Code for JAGGED ARRAY

package arrayproblems;

class Problem24 {

	public static void main(String[] args) {
		
		int[][] array2= {{1,2,3},{2,2},{1,1,1,1,1},{4,8,2,2,2,3,2,3,2}};// jagged array 2D 
		
		
		for(int i=0;i<array2.length;i++) {
			
			for(int j=0;j<array2[i].length;j++) {
				
				System.out.print(array2[i][j]+" ");
			}
			System.out.println();
		}

	}

}

In above code we can see array2 has 4 rows of different length. first row contains 3 elements, second row contains 2 elements, third row contains 5 elements and fourth row contains 9 elements.

so overall number of elements are different in each row.

so we are using 2 for loops, first one for rows and second one for iterating the elements of each row.

NOTE: array2[i].length() will give how many elements are there in ith row

You Might Like These


Dynamic Programming HACKER EARTH questions

Beginner’s friendly top 5 array questions in java

SHL off campus coding questions

Rotate Array Elements towards Right Side

Leave a Comment

Your email address will not be published. Required fields are marked *