Declaring and creating array in java

0





Declaring Array

Arrays are used typically to group objects of the same type. Arrays enable you to refer to the group of objects by a common name. 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 brackets to the left, the brackets apply to all variables to the right of the brackets.

In the Java programming language, an array is an object even when the array is made up of primitive types, and as with other class types, the declaration does not 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 elements is allocated dynamically either by a new statement or by an array initializer.

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 the array.

Creating Arrays

You can create arrays, like all objects, using the new keyword. For example, to create an array of a primitive (char) type:

s = new char[26];

The first line creates an array of 26 char values. After creation, the array elements are initialized to the default value (‘\u0000’ for characters). You must fill in the array for it to be useful;
for example:

1 public char[] createArray() {

2 char[] s;

3

4 s = new char[26];

5 for ( int i=0; i<26; i++ ) {

6 s[i] = (char) (’A’ + i);

7 }

8

9 return s;

10 }

This code generates an array in the heap memory with the upper case letters of the English alphabet. The array in heap is shown in Figure.

Untitled
The subscript that indexes the individual array elements always begins from 0 and must be maintained in the legal range: greater than or equal to 0 and less than the array length. Any attempt to access an array element outside these bounds causes a runtime exception.