Sunday, September 27, 2015

One-Dimensional Arrays

  • A one-dimensional array is, essentially, a list of like-typed variables.To create an array,you first must create an array variable of the desired type.
The general form of a one-dimensional array declaration is

type var-name[ ];

Here, type declares the base type of the array. The base type determines the data type of each element that comprises the array. Thus, the base type for the array determines what type of data the array will hold.

For example, the following declares an array named number_array with the type “array of int”:

int number_array[];

number_array is an array variable,no array actually exists. In fact, the value of number_array is set to null, which represents an array with no value.
To link number_array with an actual, physical array of integers, you must allocate one using new and assign it to number_array. new is a special operator that allocates memory.

array-var = new type[size];

type specifies the type of data being allocated.
size specifies the number of elements in the array.
array-var is the array variable that is linked to the array.

That is, to use new to allocate an array, you must specify the type and number of elements to allocate. The elements in the array allocated by new will automatically be initialized to zero. This example allocates a 10-element array of integers and links them to number_array.

number_array = new int[10];

After this statement executes, number_array will refer to an array of 10 integers. Further, all elements in the array will be initialized to zero.

Example of Declaration an Array

// Demonstrate a one-dimensional array.
class ArrayExample
{
     public static void main(String args[])
     {
          int one[];     // First Declaration Method
          one = new int[5];
          one[0] = 1;
          one[1] = 2;
          one[2] = 3;
          one[3] = 4;
          one[4] = 5;
          int two[] = { 1,2,3,4,5 }; // Second Declaration Method
          System.out.println("One " + one[3] + " Two"+two[4]);
     }
}

 

No comments:

Post a Comment

If you have any query please comment here, Will get back to you :)