|
When many items of data of the same class or type have to be stored, it is more efficient to use an array than separate variables or objects. For example, if the temperature on each day of the year had to be stored, rather than set up tempjan1, tempjan2... tempdec31 we would use the array variable the declaration would be:
double[] tempArray = new double[ 365 ];
Array is a named set of same-type variables. Each variable in the array is called an array element. The first element will have an index of 0. To reference the components of an array, use an index after the variable name.
Example:
class Arrayexamp {
public static void main(String[] args) {
int[] anArray;
anArray = new int[10];
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
System.out.println("Element at index 0: " + anArray[0]);
System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
System.out.println("Element at index 3: " + anArray[3]);
System.out.println("Element at index 4: " + anArray[4]);
System.out.println("Element at index 5: " + anArray[5]);
}
}
The output will be:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Example:
public class MyClass {
public static void main(String[] arg) {
int[] intArray = new int[10];
for (int i = 0; i < 10; i++) {
intArray[i] = 100+i;
}
for (int i = 0; i < 10; i++) {
System.out.println(intArray[i]);
}
}
}
The Output will be:
100
101
102
103
104
105
106
107
108
109
Changing Array Size:
Once an array is created, its size cannot be changed. If you want to change the size, you must create a new array and populates it using the values of the old array.
public class MyClass {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };
int[] temp = new int[4];
int length = numbers.length;
for (int j = 0; j < length; j++) {
temp[j] = numbers[j];
}
numbers = temp;
}
}
|