One-Dimensional Arrays in Java

One-Dimensional Arrays

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[ ];
  
type declare the base type of the array. The base type determines the data type of each element that comprises the array.
 
int month_days[];

new is a special operator that allocate memory. General form of new in one dimensional array is

array-var = new type[size];

Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and 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 12-element array of integers and links them to month_days
 
month_days = new int[12];



Example
//Demonstrate One Dimension Array 
public class array {
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("August has "+ month_days[7] + " days.");
}


} 
Output
August has 31 days.

Post a Comment

0 Comments