Java Array

We know that variables are used to store data in a Java program. We also know that each variable can store not more than one data item. So, what do we do if we need to store a large number of data items, say 50. Well, we can use 50 variables, one for each of the 50 data items, but we need to write 50 lines of code for setting up these variables, or we can use ARRAYs. Which will need just a single line. Most real-world programs handle vast amount of data. An array with loops can relatively handle a vast amount of data.

     An array is an object that is used to store a list of values, all of which have the same data type (Check Two Dimensional Array for complex data type). An array is a reference data type just like class. It is made of an attached block of memory. This memory space is also divided by CELLs, which hold a value. Sometimes the cells of an array are called SLOTs. Below is a picture of an array.

Array Elements
Array Elements
Important facts:
·         The cells are numbered sequentially starting at ZERO.
·         It there are n cells in an array, the index will be 0 thru n-1.

The number of variables that can be stored in an array is called the array's dimension. Each variable in the array is called an element of the array. All the elements stored in the array are accessed by simply using the variable name and the index of the element. Sometimes the index is called a subscript. The expression myArray[7] is usually pronounced “myArray-sub-seven”, which is in mathematics myArray7. Importantly, an array has a fixed number of cells. The values in the cell can be changed anytime.

Declaring Array

     Every cell of an array holds a value of the same data type. So, for example, we can have an array of int an array of double or float and so on. We can also have an array of object references. Here is a graphic representation of an array that contains seven elements, all having the same data type, int. The length of the array is the total number of elements in the array. The length of this particular array, named myArray is 7. The elements have indices starting from 0 and extending up to 6, which is one subtracted from the length of the array (7 - 1 = 6). The element at index 0 is 3, the element at index 1 is 34, and the element at index 4 is 9. We refer to the elements of the array programmatically as arrayName[index] as we will see later on. For instance myArray[0] contains the integer 3.
myArray
myArray
     The data type of an array name is specified as <data type>[], where <data type> refers to the data type of the elements the array would be storing. The square brackets indicate an array. In other words you declare an array like you'd declare any other variable except you append brackets to the end of the variable type.
Here are some examples:
     int[];
     double[];
     float[];
     String[];
The following statements show the declaration of an array named myArray, which holds int values.
     int[] myArray; or int myArray[]; // Declaration of an ARRAY
We can declare more than one arrays in a single statement.
     int[] a, b, c; // Declaration of more than one ARRAY at the same time
We can also declare a few integer variables and a few integer arrays in a single statement.
     int myArray[], b, myArray2[]; // Only a and c represent array in this statement.
Allocating Array

      Now that we have declared the array, we need to create an integer array and assign its reference to the array variable. Just like classes, arrays are created using the new keyword. The new keyword returns a reference to the array being created which is then assigned to an appropriate variable. The size of the arrays (or the length, which is the number of elements the array will hold) is also specified. So, when we create an array we need to tell the compiler how many elements will be stored in it. This example creates an array of 7 int elements, from myArray[0] to myArray[6].
     int[] myArray ; // Declare myArray to be an array of integers
     myArray = new int[7]; // Allocate an array of 7 integers
     //These are often combined in one line.
     int[] myArray = new int[7]; // Declare and Allocate
     The size of an array may be specified using integer constants as done above or by using expression that contain variables. The following array creation statements are also valid. 
     int size = 7;
     myArray = new int[size];
     myArray = new int[2 + 5];
     myArray = new int[size / 3 + 5];
Initializing Array

     Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Indexes are consecutive integers beginning with 0. Thus the array myArray above has elements_
     myArray[0];
     myArray[1];
     myArray[2];
     myArray[3];
     myArray[4];
     myArray[5];
     myArray[6];
Since we started counting at zero there is no myArray[7], and trying to access myArray[7] will generate an ArrayIndexOutOfBoundsException.


You can use array elements wherever you'd use a similarly typed variable that wasn't part of an array.
Here's how we'd store values in the arrays we've been working with:
     myArray[0] = 3;
     myArray[1] = 34;
     myArray[2] = 7;
     myArray[3] = 4;
     myArray[4] = 9;
     myArray[5] = 73;
     myArray[6] = 34;
     This step is called initializing the array or, more precisely, initializing the elements of the array. Sometimes the phrase "initializing the array" would be reserved for when we initialize all the elements of the array.
We can also initialize our array in a single line.
     int myArray[] = {3, 34, 7, 4, 9, 73, 34};
     For even medium sized arrays, it's unwieldy to specify each element individually. It is often helpful to use for loops to initialize the array. For instance here is a loop that fills an array with the squares of the numbers from 0 to 100.
     float[] squares = new float[101];
     for (int i = 0; i <= 200; i++) {
       squares[i] = i * 2;
     }
Shortcuts

We can declare and allocate an array at the same time like this:
     int[] myArray = new int[7];
     float[] myArray = new float[7];
     String[] myArray = new String[7];
     We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:
     int[] myArray = {3, 34, 7, 4, 9, 73, 34};
     float[] myArray = {0.0f, 2.2f, 3.4f, -9.87f, 59.4f, 5.0f, 127.9f};
Accessing Array Field

     When accessing an array field we have to remember that array index is starting from the 0. In our example, myArray has seven int value, so, occupied index 0 – 6. If one wants to, for example, the first element access and spend (in our example, 1), then this would do the following:
     int[] myArray = {3, 34, 7, 4, 9, 73, 34};
     System.out.println(myArray[0]);
Using a for loop is the best way to access all the elements on an array. However, we must be careful to work with array index. We don’t want ArrayIndexOutOfBoundsException. Let’s take a look at the structure of our for loop.
     int[] myArray = {3, 34, 7, 4, 9, 73, 34};
     for (int i= 0; i < myArray.length; i++) {
       System.out.println(myArray[i]);
     }
     We specified our array length with the key word myArray.length, which will ensure the exact length of the array. On the other hand, when we specify an invalid index such as a negative number or a number which is greater than or equal to the length of the array, no compilation errors occur. Rather, a run time exception, namely ArrayIndexOutOfBoundsException is thrown during runtime.

     The length of an array can be determined through the length property of the array object in the following way: 
     int[] myArray =  {3, 34, 7, 4, 9, 73, 34};
     int fullLength = myArray.length; // fullLength  = 7
NOTE that length is not a method of the array object but rather an instance variable.

Common Array Problems

Some common array programming mistakes are_

  • Runtime error: forgetting that array subscripts start with zero.
  • Compile-time error: writing myArray.length() instead of myArray.length. The length() method is used with strings, not arrays.
  • Compile-time error: Declaring an array with a size. e.g. int[7] myArray; instead of int[]myArray = new int[7];.

No comments:

Post a Comment

Grab The Button...

Grab the above button and add to your blog or website to get easy access to Virtual Species. Simply click the textbox, copy the code and paste where you want to see the button. That's it!