Jagged Array in Java
Today, in this tutorial, you get to know about Jagged array and how to create one in Java. A jagged array is basically an array of arrays. Jagged array may consist of various rows with different columns in each row. Below you can see the source code of creating a jagged array in Java.
Method to create jagged array
Follow the steps::
- Declare an array of arrays that is a 2D array with a fixed number of rows.
- For the corresponding row give the value of the number of columns.
- Take input that is where to store which number
- Display the Jagged array.
Java program to create Jagged Array
Now we will see the Java program to create a Jagged array in Java. Here first declare the array with the fixed number of rows and then for the corresponding row number of set the columns. After this, give the numbers as input that is where to store which number, and then print the Jagged array.
import java.util.Scanner; public class Jagged_array { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int JaggedArray[][] = new int[3][]; JaggedArray[0] = new int[2]; //row 1 has 2 columns JaggedArray[1] = new int[3]; //row 2 has 3 columns JaggedArray[2] = new int[1]; //row 2 has 1 column for(int i=0;i<JaggedArray.length;i++) { for(int j=0;j<JaggedArray[i].length;j++) { System.out.print("Enter element in array at position["+i+"]["+j+"]::"); JaggedArray[i][j]=sc.nextInt(); } } 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::
Enter element in array at position[0][0]::1 Enter element in array at position[0][1]::2 Enter element in array at position[1][0]::3 Enter element in array at position[1][1]::4 Enter element in array at position[1][2]::5 Enter element in array at position[2][0]::6 1,2, 3,4,5, 6,
Another way to create a jagged array without giving input is as follows. Check below source code
public class Jagged_array { public static void main(String args[]) { int JaggedArray[][] = new int[3][]; JaggedArray[0] = new int[2]; //row 1,2 columns JaggedArray[1] = new int[3]; //row 2,3 columns JaggedArray[2] = new int[1]; //row 2,1 column int flag=1; for(int i=0;i<JaggedArray.length;i++) { for(int j=0;j<JaggedArray[i].length;j++) { flag++; JaggedArray[i][j]=10*flag; } } 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(""); } } }
Here multiples of 10 are given as input. Variable Flag gets incremented every time a new position is met.
Output::
20,30, 40,50,60, 70,
Also see:: How to create a dynamic 2D array in Java
Leave a Reply