InterviewSolution
Saved Bookmarks
| 1. |
Jagged Arrays in Java |
|
Answer» Jagged arrays in Java are multidimensional arrays in which each element itself is an array of varying size as well as dimensions. Thus, they’re often referred to as array of arrays. Syntax for a two-dimensional jagged array for FIXED rows and variable columns, data_type array_name[][]= new data_type [array_size][]; (OR) data_type[][] array_name=new data_type[array_size][];Take for example a JAGGER integer array of size 4: int arr[][] = new int[4][];This row has 4 rows and each row has varying amount of columns which might later be specified. We can either declare the array and initialize the elements directly: arr[0] = new int[] {13, 42}; arr[1] = new int[] {34, 43, 95}; arr[2] = new int[] {69, 71, 83, 29}; arr[3] = new int[] {10,11};or, we can just declare the array elements without initializing them. arr[0] = new int[2]; arr[1] = new int[3]; arr[2] = new int[4]; arr [3] = new int[2];For example, PUBLIC class Example { public static void main(String[] args) { int arr[][] = new int[4][]; // creating a Jagged Array of 4 rows arr[0] = new int[]{1,2,3,4}; // the first row has 4 columns arr[1] = new int[]{5,6,7}; // the second row has 3 columns arr[2] = new int[]{10,20,30}; // the third row has 3 columns arr[3] = new int[]{2,4,2,4}; // the fourth row has 4 columns System.out.println("The elements of the Jagged Array are..."); 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(); } } }The OUTPUT is the following: $javac Example.java $java Example The elements of the Jagged Array are... 1 2 3 4 5 6 7 10 20 30 2 4 2 4 |
|