View RSS Feed

Java Array

Creating, Initializing, and Accessing an Array

Rate this Entry
by , 03-04-2012 at 11:05 AM (1613 Views)
One can create an array by the help of the new operator. In ArrayDemo program, next statement allocates the array along with quite enough memory. This is done for 10 integer elements so that to assign array to anArray variable.

Java Code:
// create an array of integers
anArray = new int[10];
In case if the given statement is missing, an error like this would be printed by compiler and also the compilation would fail.


To array’s each element, values will be assigned by the next few lines:

Java Code:
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// etc.
anArray[2] = 300;
Numerical index is used to access each element:

Java Code:
System.out.println("Element 1 at index 0: "
                   + anArray[0]);
System.out.println("Element 2 at index 1: "
                   + anArray[1]);
System.out.println("Element 3 at index 2: "
                   + anArray[2]);
To initialize and create an array, shortcut syntax may be used:

Java Code:
int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

Submit "Creating, Initializing, and Accessing an Array" to Facebook Submit "Creating, Initializing, and Accessing an Array" to Digg Submit "Creating, Initializing, and Accessing an Array" to del.icio.us Submit "Creating, Initializing, and Accessing an Array" to StumbleUpon Submit "Creating, Initializing, and Accessing an Array" to Google

Comments