Home Java Beginners Arrayexamples Java Array Initialization



Java Array Initialization
Posted on: May 28, 2007 at 12:00 AM
After declaring an array variable, memory is allocated to it. The "new" operator is used for the allocation of memory to the array object

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

C:\tamana>

Download this example.

Related Tags for Java Array Initialization:
cvariablesedtypeoperatornewnumberriathisoperaelementelementsexampletoexamevarusepeceinasmntcalocateaceemallallocalocmecattorxaxampseeatishallmplfollowandarvassrithabablallocpleplndolo


Ask Questions?    Discuss: Java Array Initialization   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.