Java Arrays Introduction

17 January 2012 By Nithya Vasudevan 923 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

Why arrays?

Suppose we have a requirement to store average mark scored by each student. To accomplish this we define different variables (identifiers) of type double to store each student’s average mark.

double student1Avg;
double student2Avg;
double student3Avg;
…
…
…
student1Avg = 60.5;
student2Avg = 85.5;
student3Avg = 94.5;
…

As you can see, it seems like a tedious task in order to create many different variables, initialize and use them especially if they are used for the same purpose.
To solve this problem, we have arrays.

What is an Array?

  • An array is a container object that holds a fixed number of elements of a single type.
  • Arrays are always objects whether it is declared to hold primitive or object.
  • The length of an array is established when the array is created. After creation, its length is fixed.

Steps:

Following are the steps involved in using an array.

  1. Declare an array
  2. Construct an array i.e.) allocating memory on the heap
  3. Initialize an array with elements
  4. Access array elements.

Tags: ,