Arrays
An array is simply a sequence of either objects or primitives that are all the same type and are packaged together under one identifier name. Arrays are defined and used with the square-brackets indexing operator [ ] :
int[] a1;
There are primarily 2 types of Arrays.
1. One Dimensional Array
2. Two Dimensional Array
1. One Dimensional Array
One dimensional array are the arrays which contain only 1 row and many number of columns. like [1,2,3,4,5,6….]
You can also put the square brackets after the identifier to produce exactly the same meaning:
int a1[]; int a2[] = new int[5]; // limit of array is defined as 5
There are situations in which we want to declare an array without mentioning it’s size. In those cases we do this as :
int[] a1 = { 1, 2, 3, 4, 5 };
2. Two Dimensional Array
multidimensional arrays are arrays of arrays. They are formed with Rows and Columns.They are declared as :
int twoDArray[][] = new int[4][5]; // this array contains 4 rows and 5 columns
Jagged Arrays
Jagged arrays are the arrays which are not limited to a particular order. Suppose we want 4 columns in first row, 2 columns in 2nd row and 3 columns in 3rd row. like this will look like this :-
1 2 3 4 1 2 1 2 3
These types of arrays are handled in java special syntax. Let’s review a program that demonstrate the arrays functionality
public class JavaArrays { public static void main(String[] args) { // 1 Dimensional Array int arr1[] = { 1, 2, 3, 4, 5, 6 }; // 1 dimensional array for (int i = 0; i < 6; i++) System.out.println(arr1[i]); // printing array values // 2 Dimensional Array int arr2[][] = new int[2][3]; // dimensional array of 2 rows and 3 // columns, all elements will be // initialized to 0 for (int row = 0; row < 2; row++) // loop for iterating through array rows for (int col = 0; col < 3; col++) // loop for iterating through array columns System.out.println(arr2[row][col]); // printing array value // Jagged Arrays int arr3[][] = new int[3][5]; arr3[0] = new int[4]; // four columns assigned to 1st row arr3[1] = new int[2]; // two columns assigned to 2nd row arr3[2] = new int[3]; // three columns assigned to 3rd row for (int row = 0; row < 3; row++) { for (int col = 0; col < arr3[row].length; col++) { arr3[row][col] = 200; // assign arbitrary value to each element // of jagged array } } // printing Jagged arrays value for (int row = 0; row < 3; row++) { for (int col = 0; col < arr3[row].length; col++) { System.out.print(" " + arr3[row][col]); } System.out.println(); // to output a blank line } } }