Arrays in Java
Arrays are used to store collection of data. In other words, arrays are collection of variables stored under one name by manipulating indexes. Instead of declaring var1, var2, var3… you can declare one array var[0],var[1], var[2]… to represent indivisual variables.
Single Dimension Array
Declaring Array
dataType[] arrayRefVar; or dataType arrayRefVar[]; int[] mylist; or int mylist[];
Creating Array
arrayRefVar = new dataType[size]; mylist = new int[5];
Declaration and Creation in one step
dataType[] arrayRefVar = new dataType[size]; or dataType arrayRefVar[] = new dataType[size]; int [] mylist = new int[5]; or int mylist[] = new int[5];
Initializing Array
Declaring, creating and initializing in one step
int[] arr = {1,2,3};
or
int[] arr = new int[3]; arr[0] = 1; arr[1] = 2; arr[2] = 3;
Note :
- Once an array is created then its size is fixed. To find the size of an array you can use
arrayRefVar.length; mylist.length;
- Declaration style
dataType[] arrayRefVar;
is preffered. - In array creation process, its elements are assigned default values such as 0 for numeric and false for boolean
- The indices of array are 0-based, its start from 0 to (n-1) where n is the size of an array
- Each element in the array is represented using the following syntax, known as an indexed variable
arrayRefVar[index];
- Shorthand code must be in one statement
Double Dimension Array / Multi Dimensional Array
To represent a table or matrix you can use double dimensional array.
Declaring Array
dataType[][] arrayRefVar; or dataType arrayRefVar[][]; int[][] mylist; or int mylist[][];
Creating Array
arrayRefVar = new dataType[size][size]; mylist = new int[5][5];
Declaration and Creation in one step
dataType[][] arrayRefVar = new dataType[size][size]; or dataType arrayRefVar[][] = new dataType[size][size]; int[][] mylist = new int[5][5]; or int mylist[][] = new int[5][5];
Initializing Array
Declaring, creating and initializing in one step
int[][] arr = {{1,2,3}, {4,5,6}, {7,8,9},};
or
int[][] arr = new int[3][3]; arr[0][0] = 1; arr[0][1] = 2; arr[0][2] = 3; arr[1][0] = 1; arr[1][1] = 2; arr[1][2] = 3; arr[2][0] = 1; arr[2][1] = 2; arr[2][2] = 3;
Ragged Array
Every row in two dimensional array represents a single dimension array. In this case, the size of two rows can be different. Such arrays are known as ragged array. Have a look at this example, size of first row is 3, size of 2nd row is 2 and 3rd size is 1.
int[][] arr = {{1,2,3}, {4,5}, {6},};
Reference
[1] Introduction to Java Programming, Comprehensive Version plus MyProgrammingLab with Pearson eText (9th Edition)
No Responses