Arrays In JAVA
• An array is a group of liked-typed variables
referred to by a common name, with individual variables accessed by their index.
• Arrays are:
1) declared
2) created
3) initialized
4) used
• Also, arrays can have one or several dimensions.
Array Declaration
Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
• Two styles of array declaration:
type array-variable[];
or
type [] array-variable;
Array Creation
• After declaration, no array actually exists.
• In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
• This creates a new array to hold size elements of type type, which reference will be kept in the variable array-variable.
Array Indexing
• Later we can refer to the elements of this array through their indexes:
• array-variable[index]
• The array index always starts with zero!
• The Java run-time system makes sure that all array indexes are in the correct range, otherwise raises a run-time error.
Array Initialization
• Arrays can be initialized when they are declared:
• int monthDays[] =
{31,28,31,30,31,30,31,31,30,31,30,31};
• Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all
specified elements
Multidimensional Arrays
Multidimensional arrays are arrays of arrays:
1) declaration: int array[][];
2) creation: int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };