Title: Arrays
1Arrays
Contents
- Declaration and Definition of an array
- Initialization of an array
- Accessing the elements of an array
- Traversing an array
2Arrays
Declaration and Definition
An array is a fixed amount of contiguous memory
that is allocated to hold data of a specified
type. An array, for example, may hold a sequence
of integers. To declare an array and allocate
memory, the programmer must specify
The type of data that will be contained in the
array
A name for the array
The length of the array (The number of integers
in the sequence)
Example Construct an array to contain a
sequence of 10 integers
int intArray
intArray new int 10
intArray
0
3Arrays
An array object (such as intArray) holds a handle
(we avoid using the word pointer in java) to the
first byte of allocated storage.
In the example on the previous slide, no memory
was allocated during the declaration, so a null
value was assigned to the variable intArray.
int intArray
Default initial array values are all 0
intArray new int 10
An amount of memory equal to 10 sizeof (int)
40 bytes is allocated with the address of the
first byte of this allotment stored in the array
variable intArray.
4Arrays
Initialization of arrays
An array may be initialized during declaration.
String composers Bach, Mozart,
Beethoven, Chopin, Liszt
List elements match the declared type
The size of the array is determined by the number
of items in the sequence
5Arrays
Accessing values stored in an array
An array is an indexed sequence of a single kind
of object.
Elements of the array are located by their
position (index value) in the sequence.
0 1 2
3 4
The numbering of the elements in a java array
begins with 0
6Arrays
To access one of the elements of an array you
specify the name of the array and the index of
the element.
examples
System.out.println(composers1)
Mozart
composers3 Hadyn
Assignment to the 4th position
7Arrays
Traversing an array
Every array has a public length attribute that
can be accessed using dot notation.
composers.length //has a value of 5
The array has a length of 5 elements which are
contained in the range of 0 composers.length
- 1
Example of array traversal
int size composers.length for (int i 0 i lt
size i) //do something
Print the list of composers
Initialize all elements to Bach