Java-Programming-Docs Help

Declaring and Creating Arrays

Remember that arrays are objects that store a set of elements in an index−accessible order. Those elements can either be a primitive datatype, such as an int or float, or any type of Object. To declare an array of a particular type, just add brackets ([ ]) to the declaration:

int[] variable;

For array declaration, the brackets can be in one of three places:

int[] variable;int[] variable;int variable[];

The first says that the variable is of type int[]. The latter two say that the variable is an array and that the array is of type int

Once you have declared the array, you cna create the array and save a reference to it. The new operator is used to create arrays. When you create an array, you must specify it length. Once this length is set, you cannot change it. As the following demonstrates, the length can be specified as either a constant or an expression:

int[] variable = new int[10];
int[] createArray(int size) { return (new int[size]); }

You can combine array declaration and creation into one step:

int[] variable = new int[10];

Once the array has been created, you can fill it up. This normally done with a for-loop or with separate assignment statements. For instance, the following will create and fill a three-element array of names:

public class StringArray { public static void main(String[] args) { String names = new String[3]; names[0] = "Leonardo"; names[1] = "da"; names[2] = "Vinci"; } }
    Last modified: 16 July 2024