Declaring an array

17 January 2012 By Nithya Vasudevan 705 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

Syntax: One Dimensional Array

Method 1Type[] arrayReferenceName; //Recommended
Method 2Type arrayReferenceName[]; //Legal, but not recommended



Syntax: Two Dimensional Array

Method 1Type[] [] arrayReferenceName; //Recommended
Method 2Type arrayReferenceName[] []; //Legal, but not recommended

Type can be either primitive or reference.

Examples,

Primitive ArrayReference Array
int[] numbers;
double[] studentAvgs;
char[] studentGrades;
long[] pincodes;

int[] [] numbers;
double[] [] averages;

String[] studentNames;
Threads[] threads;
Person[] persons;
Animal[] animals;
Fruits[] fruits;
Vehicle[] vehicles;

String[] [] strings;
Animal[] [] animals;

Method 1:
You declare an array by specifying the type of the element it will hold followed by square bracket then array reference name.

char[] studentGrades;

This allows better readability and anyone reading the code can easily tell that studentGrades is a reference to a char array object and not a char primitive.
Method 2:
You declare an array by specifying the type of the element it will hold followed by square bracket to the right of the array reference name.

char studentGrades[]; or char studentGrades [];
String[] strings[]; //two dimensional array. Legal but not recommended.

This is legal declaration but less readable. Space between array reference name and [] is legal but bad.

  • An array of type int (int[]) says that each element is of type int, i.e.) each element is just a int variable. Similarly, an array of type Person (Person[]) specifies that each element it can hold is of type Person.
  • You can also declare an array by assigning default null value.
    int[] numbers = null;

Tags: , ,