In programming languages, an array is a way of storing several items (such as integers). These items must have the same type (only integers, only strings, ...) because an array can not store different kinds of items. Every item in an array has a number so the programmer can get the item by using that number. This number is called the index. In some programming languages, the first item has index 0, the second item has index 1 and so on. But in some languages, the first item has index 1 (and then 2, 3, ...).
When the programmer creates an array, he/she must give the size of the array. This is the number of items that can be stored in the array. If the programmer wants to store more items then he/she must create a new array. This is because the size of an array can not be changed.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
anArray = new int[10]; // allocates memory for 10 integers
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;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
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]);
System.out.println("Element at index 6: " + anArray[6]);
System.out.println("Element at index 7: " + anArray[7]);
System.out.println("Element at index 8: " + anArray[8]);
System.out.println("Element at index 9: " + anArray[9]);
}
}
The output from this program is:
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
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
ex.Array 2d
class DemoArray2D {
public static void main(String[] args) {
int[][] duaD = new int[2][3];
int k = 1;
for(int i=0; i<2; i++) {
for (int j=0; j<3; j++) {
duaD[i][j] = k * 10;
System.out.print(duaD[i][j]);
if (j < 2) System.out.print(" ");
k++;
}
System.out.println();
}
}
}
Sunday, March 20, 2011
Array in java
Labels:
computer
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment