Previous | Home | Next |
One dimensional array is a list of variables of same type that are accessed by a common name. An individual variable in the array is called an array element. Arrays forms a way to handle groups of related data. A one-dimensional array is a linear list of elements of the same type. To create an array, first you must declare an array variable of required type.
- Declare the Array
- Allocation Memory for its Elements
Syntax: type array-name[]; // no memory allocation takes place in declaration or type []array-name;
Where type defines the data type of array element like int, double etc.
array-name is the name of array.
Note: That declaration does not actually create an array. it only declares a reference.
In java, initialize an array can be done by using new keyword.
Syntax: array-name=new type[Size] //Size must be a constant or a variable
Note:All the elements of array will be automatically initialized to zero.
Array index start with zero.
Example : This example shows how to declare initialize and display an array.
// Declaration of allocating memory to an array int a[] = new int[3]; // Initializing elements a[0] = 1; a[1] = 2; a[2] = 3; //Display array elements System.out.println(a[0]); System.out.println(a[1]); System.out.println(a[2]); // Or Use for loop to display elements for (int i = 0; i < a.length; i = i + 1) { System.out.print(a[i]); System.out.print(" "); }
Example :
class Array { public static void main(String args[]) { int a[]={10,20,30,40,50}; for(int i=0;i<a.length;i++) System.out.println(a[i]); } }
Output :
10 20 30 40 50
Previous | Home | Next |