Search Java Programs

Tuesday, January 19, 2010

Java Array Initialization

After declaring an array variable, memory is allocated to it. The "new" operator is used for the allocation of memory to the array object. The correct way to use the "new" operator is

String names[];

names = new String[10];

Here, the new operator is followed by the type of variable and the number of elements to be allocated. In this example [] operator has been used to place the number of elements to be allocated.

Lets see a simple example of an array,


public class Sum
{
public static void main(String[] args)
{
int[] x = new int [101];
for (int i = 0; i<x.length; i++ )
x[i] = i;
int sum = 0;
for(int i = 0; i<x.length; i++)
sum += x[i];
System.out.println(sum);
}
}

In this example, a variable 'x' is declared which has a type array of int, that is, int[]. The variable x is initialized to reference a newly created array object. The expression 'int[] = new int[50]' specifies that the array should have 50 components. To know the length of the Array, we use field length, as shown.

Output for the given program:

C:\tamana>javac Sum.java

C:\tamana>java Sum
5050

No comments:

Post a Comment

Website Design by Mayuri Multimedia