Java Arrays
Java Arrays
• Suppose there are three variables of type int with different identifiers for
each variable.
int number1;
int number2;
int number 3;
number1 = 1;
number2 = 2;
number3 = 3;
• This seems like a tedious task in order to just initialize and use the
variables especially if they are used for the same purpose.
Arrays
• An array is a sequence of memory locations for storing data set
out in such a way that any one of the individual locations can be
accessed by quoting its index number.
0 1 2
number: 1 2 3
• The individual items within an array are called elements.
Declaring Java Arrays
• To declare an array, write the data type, followed by a set of square brackets [], followed by the
identifier name.
ElementType[] arrayName;
Example:
int[] x;
int[] ages;
Or equivalently
int x[];
int ages[];
Initializing Array Variables
• To initialize an array, you use the new operator to allocate memory for
objects. The new operator is followed by the data type with the number of
elements to allocate specified. The number of elements to be allocated is
placed within the [] operator.
Example:
or
Example:
Example:
• Creates an array of 4 double variables initialized to the values {100, 90, 80, 75}.
• Creates an array of strings with identifier days and initialized. This array contains 7
elements.
• An array of 15 doubles
• An array of 20 strings
Accessing an Array Element
Example:
3.You cannot resize an array. However, you can create a new array
of a different size, copy the desired data into the new array, and
assign the new array to the array variable.
Array Length
• All array indices begin at 0. The number of elements in an array
is stored as part of the array object in the length attribute.
Example:
• //integer array 512 x 128 elements
int[][] twoD = new int[512][128];
• //character array 8 x 16
char[][] twoD = new char[8][16];
Example:
• To access the first element in the first row of the array dogs, we
write,
System.out.print(dogs[0][0]);