MathBits.com
Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use

 

Initializing Arrays

Using the assignment operator (=) to initialize an array (the "drudge" method):

int [ ] temps = new int [ 3 ];
temps[0] = 78; 
//filling one element at a time
temps[1] = 88;
temps[2] = 53;

Works fine until the array needs to contain a large amount of data.

 

Using a for loop and user input to initialize an array:

int [ ] nums = new int [ 8 ];
for(int ctr = 0; ctr < 8; ctr++)
{
     
//fill one element at a time
      nums[ctr] = Console.readInt("Please enter a number:");
     
}

Warning!

Array subscripts start with the
 number 0
 (not 1).



Initialize at time of declaration - filling by list.
It is possible to fill an array at the time of declaration.

double [ ]  temperature = { 13.5, 18.4, 19.6, 21.4};

The array length (size) will be automatically set to the minimum that will hold the given values.  The statement above is equivalent to the following statements:

double [ ] temperature = new double [4];
temperature[0] = 13.5;
temperature[1] = 18.4;
temperature[2] = 19.6;
temperature[3] = 21.4;

 

Declare an array of strings:

String [ ] list = new String [ 2000];
for ( i = 0; i < 2000; i++)
{
     list [ i ] = Console.readLine("Enter string: " );

} 

 


Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use