Tuesday, May 17, 2011

Defining or Allocating one dimensional array in java

We saw declaration of array here. However, this statement only declares the variable a. It does not yet initialize a with an actual array. You use the new operator to create the array.

int[] a = new int[100];

This statement sets up an array that can hold 100 integers.

The array entries are numbered from 0 to 99 (and not 1 to 100). Once the array is created, you can fill the entries in an array, for example, by using a loop:

int[] a = new int[100];
for (int i = 0; i < 100; i++)
a[i] = i; // fills the array with 0 to 99

No comments:

Post a Comment