An array is a derived data type, which can be used for storing multiple values.
If an application requires multiple values, then we can store those multiple values by declaring multiple variables. If we declare multiple variables in a program then the code size will increase and readability will be reduced.
In order to reduce the code size, and improve the readability of the code, we take the help of arrays. Arrays in java language are classified into two types. They are
- Single dimension array
- Multi dimension array
Single dimension Array
Single dimension array is a collection of multiple values represented the form of single row or single column.
Syntax for declaring a single dimension array
datatype arrayName[];
each pair of sequence bracket represents one dimension.
The name of the array can be any valid java identifier
Rule1:
At the time of array declaration we can specify the pair of [] either before the array name or after the array name
Example
int rollNo[];
double[] marks;
char []grade;
boolean result[];
Rule2: At the time of array declaration we should not specify the size of the array.
Syntax for declaring a single dimension array
datatype arrayName[]=new datatype[size];
or
datatype arrayName[];
arrayName= new datatype[size];
Example
int arr[]=new int[10]
or
int arr[];
arr=new int[10];
Rule:
Specifying the size of the array at the time of array creation is mandatory and it should be of byte, short, int, char type only.
The size of the array must be positive number. If a negative number is specified , then we get a runtime error called NegativeArraySizeException.
When an array is created, the memory for that array will be allocated in sequential memory locations. The amount of memory allocated to an array depends upon the size of the array and the size of the datatype of the array. Once the memory for the array is allocated, all the array elements will be initialized automatically with default values.
An array contains multiple values and for the entire array we have only one name. In order to access the array elements we take the help of index position. The index position will always begin with 0. The range of the index position will be 0 to size -1.
Every array is internally an object and it contains a default variable called length, which represents the size of the array.
int arr[]= new int [];
arrayName[index]=starting address of the array + index* size of array type
arr[0]=1000+0*4=1000
arr[1]=1000+1*4=1004
arr[5]=1000+5*4=10020
Syntax for accessing the array elements
arrayName[index]
Example
arr[0]
arr[1]
When we are accessing the array elements, we are supposed to specify the index position within the range otherwise we get runtime error called ArrayIndexOutOfBoundException.
Syntax to assign a value to an array element:
arrayName[index]=value;
Example
arr[0]=10;
arr[1]=20;