One Dimensional Array

An array is a group of contiguous or related data items that share a common name. An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots. Arrays of any type can be created and may have one or more dimensions.

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 is the data type of an array which is to hold. By specifying declaring array no array actually exists. To create actual array you must allocate one using new and assign it to the array-variable. Its general form is given below:
array-var  =  new type[size];

Here size specifies the number of elements in the array. In program we will create an array of month days named month_days and after that we will display the number of days of specified month.

class ArrayDemo {

 public static void main(String[] args) {

  int month_days[];
  month_days = new int[12];

  month_days[0] = 31;
  month_days[1] = 28;
  month_days[2] = 31;
  month_days[3] = 30;
  month_days[4] = 31;
  month_days[5] = 30;
  month_days[6] = 31;
  month_days[7] = 31;
  month_days[8] = 30;
  month_days[9] = 31;
  month_days[10] = 30;
  month_days[11] = 31;
  System.out.println("Aril has " + month_days[3] + " days.");
The output is given below:
C:\>java ArrayDemo
Aril has 30 days.

No comments:

Post a comment