Arrays - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

Arrays

Description:

The array holds handles to the five string objects. List elements match the declared type ... Elements of the array are located by their position (index value) ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 8
Provided by: jamest92
Category:
Tags: arrays | elements | five

less

Transcript and Presenter's Notes

Title: Arrays


1
Arrays
Contents
  1. Declaration and Definition of an array
  2. Initialization of an array
  3. Accessing the elements of an array
  4. Traversing an array

2
Arrays
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
3
Arrays
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.
4
Arrays
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
5
Arrays
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
6
Arrays
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
7
Arrays
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
Write a Comment
User Comments (0)
About PowerShow.com