Declaring an array

Syntax: One Dimensional Array

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



Syntax: Two Dimensional Array

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

Type can be either primitive or reference.

Examples,

Primitive Array Reference 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;

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.