Karla News

Tutorial – Declaring Array in JAVA

You can create variable of built in data type and reference variables easily. But, what will you do if you have to create many variables of the same data type? You have to declare each variable individually. But it will waste a lot of time. Another option of creating many variables either built in or reference data type is “ARRAY”.

For declaring one dimensional array:

Array is used typically to group objects of same data type. Array enables you to refer to a group of objects by a common name; you don’t have to remember all variable names. You can declare arrays of any type, either primitive or class:

Char [] s;

Point [] p; // where point is a class

When declaring arrays with the bracket to left, the brackets apply to all variables to the right of brackets.

In the JAVA programming language, an array is an object even when the array is made up of primitive type, and as with other class types, the declaration does create the object itself. Instead, the declaration of an array creates a reference that you can use to refer to an array. The actual memory used by the array element is allocated dynamically either by a new statement or by an array initialize.

You can declare arrays using the square brackets after the variable name:

Char s [];

Point p [];

This is standard for c, c++ and the JAVA programming language. This format leads to complex forms of declaration that can be difficult to read.

The result is that you can consider a declaration as having the type part on the left, and the variable name on the right. You will see both formats used, but you should decide on one or the other for your own use. The declarations do not specify the actual size of array.

See also  Analysis of Emily Dickinson's "39 (49)"

For declaring the multidimensional array:

For declaring multidimensional arrays in the JAVA programming language does not provide in the same way that other language do. Because you can declare an array to have any base type, you can create arrays of arrays (and arrays of arrays of arrays, and so on). The following example shows a two dimensional arrays:

Int [] [] twodim = new int [4] [];

Twodim [0] = new int [5];

Twodim [1] = new int [5];

The object is created by the call to new is an array that contains four elements. Each element is a null reference to an element of type array of int and you must initialize each element separately so that each element points to its array.

Reference: