Home Java Beginners Arrayexamples Java Array Initialization
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java Array Initialization

Advertisement
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.

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 28, 2007

Related Tutorials

Ask Questions?    Discuss: Java Array Initialization   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
MANTOMBAZANA NKOSI
September 22, 2011
Information Technology

HOW DO WE INTIALISE ARRAYS AND HOW DO WE ACCESS THE VALUE OF ARRAYS
Pann Saradeth
November 17, 2011
I need more

I like it!!!.
Pann Saradeth
November 17, 2011
I need it more

I like it!!!.
ameerbasha
December 4, 2011
Arrays

Can we insert an element if array is declared as Final. Ex: final int arr[] = {1,2,3,4,5,6}; arr[4]//it is possible
Ankit
April 29, 2012
Java Array Initialization

public static void main(String[] args) { int [] x = new int[101]; int sum =0; for (int i =0 ; i< x.length; i++) { x[i]= i; sum += x[i]; } System.out.println(sum); } } Ans : 5050
maricar
September 21, 2012
information system 14

java array is a kind of language that you can easily run.
DMCA.com