Arrays in Java
An Array is a group of related data items that share a common name. The extend of an array in Java is established when the array is formed. Once the array is created, the length is fixed.
|
Array Index and Elements |
A loop with the subscript as the control variable can be used to read the entire array.
One Dimensional Arrays
A list of items can be given one variable name using only one subscript is called one dimentional array.
- Creating an one dimentional array in Java
Syntax: type arrayname[];
type[] arrayname;
Both the above statements do the same operation. Creation of an array in Java is a three step process.
i) Array Declaration
ii) Creation of Memory Location
iii) Assign Values
i) Array Declaration
Arrays in Java can be declared in two forms as shown in the syntax above.
Example for Array Declaration:
int [] serialnumber;
int serialnumber[];
ii) Creation of Memory Location
Create memory location for the declared array.
Example for creation of memory location:
serialnumber = new int[5];
The above statement create 5 int type locations for the array serialnumber. We can also declare and create memory location using a single statement in Java.
Example: int serialnumber[] = new int[5];
iii) Assign Values
Assign values means nothing otherthan initialization of arrays.
Syntax for initializing an Array:
arrayname[subscript] = value;
type arrayname[] = {list of values};
First line assign values to particular element in the array and the second statement shows the syntax for assigning a list of values in to an array.
Example for initializing an array:
serialnumber[0]=1200;
serialnumber[1]=1201;
serialnumber[2]=1202;
serialnumber[3]=1203;
serialnumber[3]=1204;
Above five statements can be replaced with the single statement below.
int[] serialnumber = {1200, 1201, 1202, 1203, 1204};