Defining and Declaring ArraysAn array stores a group of data items all of the same type.An array is an object.An array variable does not actually store the array -it is a reference variable that points to an array object.Declaring the array variable does not create an array object instance; it merely creates the reference variable -the array object must be instantiated separately.Once instantiated, the array object contains a block of memory locations for the individual elements.If the individual elements are not explicitly initialized, they will be set to defaultvalues.Arrays can be created with a size that is determined dynamically (but once created, the size is fixed).Declare an array variable by specifying the type of data to be stored, followed by square brackets [].dataType[] variableName;You can read the []as the word "array".To declare a variable for an array of integers:int[] nums;...which you can read as "intarray nums".To declare a variable for an array of Stringobjects:String[] names;...which you can read as "Stringarray names" -the array holds Stringreferences.You may also put the brackets after the variable name (as in C/C++), but that is less clearly related to how Java actually works.int nums[]; // not recommended, but legalBut, that syntax does allow the following, whichis legal, but seems like a bad practice.int nums[], i, j; // declares one array and two single int values.
Instantiating Arrays Instantiate an array object using new, the data type, and an array size in square brackets.int[] nums ;nums = new int[10];The second line constructs a new array object with 10 integer elements,all initialized to 0,and stores the reference into nums.int[] moreNums;int size = 7;moreNums = new int[size];You can declare and instantiate all at once:String[] names = new String[3];The elementsof the array, Stringreferences, are initialized to null.As objects, arrays also have a useful property: length:In the above example, names.lengthwould be 3.Theproperty is fixed (i.e., it is read-only).You can reassign a new arrayto an existing variable:int[] nums;nums = new int[10];nums = new int[20];The original ten-element array is no longer referenced by nums, since it now points to the new, larger array.
No comments:
Post a Comment