Friday, September 18, 2015

Declaring and Creating Arrays in Java

Array objects occupy space in memory. Like other objects, arrays are created with keyword

new. To create an array object, you specify the type of the array elements and the number

of elements as part of an array-creation expression that uses keyword new. Such an expression



returns a reference that can be stored in an array variable. The following declaration

and array-creation expression create an array object containing 12 int elements and store

the array’s reference in array variable c:

int[] c = new int[ 12 ];

This expression can be used to create the array shown in Fig. 7.1. When an array is created,

each element of the array receives a default value—zero for the numeric primitive-type elements,
 
false for boolean elements and null for references. As you’ll soon see, you can



provide nondefault initial element values when you create an array.

Creating the array can also be performed in two steps as follows:
int[] c; // declare the array variable

c = new int[ 12 ]; // create the array; assign to array variable


Common Programming :
 
 
 
In an array declaration, specifying the number of elements in the square brackets of the
 
declaration (e.g., int[12] c;) is a syntax error.

Good Programming Practice :
 
 
 
For readability, declare only one variable per declaration. Keep each declaration on a separate

line, and include a comment describing the variable being declared

A program can declare arrays of any type. Every element of a primitive-type array contains

a value of the array’s declared element type. Similarly, in an array of a reference type,

every element is a reference to an object of the array’s declared element type. For example,
 
every element of an int array is an int value, and every element of a String array is a reference

to a String object.
 
 

1 comment:

  1. This was another good class . I'm enjoying it , thank you .

    ReplyDelete