Array
Array
Introduction to Arrays
• We have used Primitive Data types to store attributes of a class
• int, double, Boolean, String
• Primitive variables are designed to hold only one value at a time.
• Arrays allow us to create a collection of values of the same type.
• An array can store any type of data but only one type of data at a
time.
• An array is a list of data elements
Introduction to Arrays
• An array is an object so it needs an object reference..
int[] numbers;
Numbers
0 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Array element values are initialised to 0.
Array indexes always start at 0.
Declaring Arrays
• numbres[0] = 20;
Numbers
20 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Copying Arrays
• This is not the way to copy an array.
int[] array1 = { 2, 4, 6, 8, 10 };
int[] array2 = array1; // This does not copy
array1.
2 4 6 8 10
array1 holds an
Address
address to the array
array2 holds an
Address
address to the array
Copying Arrays
• You cannot copy an array by merely assigning one reference variable
to another.
• You need to copy the individual elements of one array to another.
int[] firstArray = {5, 10, 15, 20, 25 };
int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
secondArray[i] = firstArray[i];
• This code copies each element of firstArray to the
corresponding element of secondArray.
Accessing elements of an Array
• For loops are very useful for visiting the elements of an array
• for loops help us to move from one element to the next
QUESTION
• What elements does the data array contain after the following
statements?
• int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
Rows Columns
2-D representation
• It is a table
• First dimension: row
• Second dimension: columns
0 1 2 3
0
marks[2][1] = 55;
1
2 55
…
19
Accessing 2-D arrays
Number of rows
• Initialisation of the marks array