Declaring an Array

declaring array

Declaring an Array 

Declaring  array does not actually creates an array , it simply tells the compiler that this variable is holding a specified type of array.

  • Like declaration of variables of other types , an array declaration has two components : the array’s type and the arrays’ name
  • The array’s type is written as type[] , where type is the data type of the contained elements. The square brackets are the special symbol indicating that this is an array kind.
  • The size of the array is not the part of this type , which is why the square brackets are empty.
  • An array’s name can be anything you want but it should meet all the rules and naming conventions.
  • Declaration does not actually creates an array , it simply tells the compiler that this variable is holding a type of array.

Syntax :  type[] var-name ;

Example :    1. int[] numbers;

                      2.  int numbers[]

  • The square brackets can also be placed after the variable-name , but that is not recommended

Creating , initializing and accessing an array 

  • Creating an array is done by the use of the new operator. 

For example : int[] numbers = new int[5];

  • In the above example an array of type int of size 5 is created. Now numbers array can store up to 5 int type of values.
  • Declaring and creating an array is done in a single step. But for our programming needs , the programmer may declare an array at the starting without the knowledge of size and creates and array in the middle of the program when it is needed. 

 

Initializing an array

  • Initializing an array is nothing but storing the values to an array.

For Example 

numbers[0] = 100;

 // inside the square brackets is the value of the index. i.e at index 0 , the value 200 is stored.

numbers[1]=200;

numbers[2] = 300;

numbers[3]= 400;

numbers[4] = 500;

Each array element is accessed by its index value

System.out.println("Element at index 0 is : " + numbers[0]);

System.out.println("Element at index 0 is : " + numbers[1]);

System.out.println("Element at index 0 is : " + numbers[2]);

System.out.println("Element at index 0 is : " + numbers[3]);

System.out.println("Element at index 0 is : " + numbers[4]);

But you can create and initialize an array in one single step 

int[] numbers = {100,200,300,400,500};

/* here the length of the array is determined by providing the values between 
the curly braces and separated by commas. */

3 thoughts on “Declaring an Array

  1. I like what you guys are up also. Such clever work and reporting! Carry on the excellent works guys I¦ve incorporated you guys to my blogroll. I think it’ll improve the value of my site 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *