Declaring Methods  «Prev  Next»


Lesson 3Arrays
ObjectiveDescribe how arrays are declared and initialized.

Declare and initialize Arrays in Java

Declaring arrays

When an array is declared, the array's dimensions must be specified using a pair of matching braces (i.e., []).
Java provides a lot of lexibility on how these braces may be placed. They may be placed to the right of the array type or to the right of the array identifier. Zero or more spaces may be placed around each brace. Each of the following array declarations are equivalent:

int[]i; 
int[] i; 
int []i; 
int i[]; 
int [ ] i; 
int i [ ]; 		       

To add to this confusion, multidimensional arrays may be specified with brace sets to the left or right of the array identifier.
int[] j[]; 
int []j[]; 
int[][] j; 
int j[][]; 


Once an array is declared, it must be created. This can be done using an array initializer or using the new operator followed by an array dimension expression. Array initializers are used as follows:
int[] i = {1, 2, 3, 4, 5};

The above declares, creates, and initializes an array of five int values. Arrays of arrays may be specified by nesting array initializers.
int[][] i = {{1,2,3}, {4,5,6}, {7,8,9}};

Array initializers work well for small arrays but are impractical for arrays that contain more than a few elements. To create larger arrays, use the new operator followed by the array type and the array size within braces.

String[] s = new String[100];

The above statement declares and initializes an array of 100 String objects. You can also specify multidimensional arrays using this notation:
String[][] s = new String[200][50];

The above notation is also equivalent to the following:

String[][] s = new String[200][];
for (int i = 0; i < 200; i++)
  s[i] = new String[50];

One array can be copied to another array by using the method
static void arraycopy(Object src, int srcPos, 
Object dest, int destPos, int length) 
arraycopy
When an array is created, its elements are automatically initialized as described in the Module "Java Language Fundamentals."

Java Array Declarations - Quiz

Click the Quiz link to check your understanding of variable declarations.
Java Array Declarations - Quiz