Creating, Initializing, and Accessing an Array
by , 03-04-2012 at 10:05 AM (786 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.
In case if the given statement is missing, an error like this would be printed by compiler and also the compilation would fail.Java Code:// create an array of integers anArray = new int[10];
To array’s each element, values will be assigned by the next few lines:
Numerical index is used to access each element:Java Code:// initialize first element anArray[0] = 100; // initialize second element anArray[1] = 200; // etc. anArray[2] = 300;
To initialize and create an array, shortcut syntax may be used: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]);
Java Code:int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };









Email Blog Entry
License4J 4.0
05-22-2013, 12:23 AM in Java Software