Notes
Outline
COM 1100
1/22/02
Class 8
Today’s class
Array Declaration
Array Initialization
Multidimensional Arrays
Accessing arrays
Codewarrior demonstration
Lab discussion
Array Declaration
int num[];
num = new int[256];
Once an array is created, its size cannot be changed
int num[256];
This will NOT work
Will work in C and C++, but not in Java
Array Initialization
int b[] = { 0, 1, 2, 3, 4};
String wkdays[] = {“Mon”, “Tue”, “Wed”, “Thu”, “Fri”};
Declares the array and initialize it one step
Multidimensional Arrays
A Multidimensional Array is sometimes called an array of arrays
Can be visualized as a 2-d table, or 3-d cube
Arrays do not have to be the same size
int num[][] = new int[124][256];
Sample Initializations
int myTable[][] = new int[][]{
new int[] {0},
new int[] {0,1},
new int[] {0,1,2}};
int myTable[][] = new int[][]{
{0},
{0,1},
{0,1,2}};
Movable Brackets
The brackets in an array declaration can move around
Traditionally, they follow the variable name, but this is not a requirement in the language
The following are all valid array declarations:
Int a[];
Int [] b = {a.length, 2, 3};
Char c [] [] = new char[12][32];
Char[] [] e;
Accessing Array Elements
An element stored in an array is accessed by its subscript
The element stored in position 24 of array num would be accessed by num[24]
Arrays are all accessed numerically
To access an element in a 2-d array you need two numbers
Num[12] [24] would return the element stored in position 24 of the array stored
Array Index Starts at Zero
All array indexes start at zero
An array with 256 elements can be accessed from num[0] to num[255]
Trying to access num[256] in this array will return an array out of bounds error
Finding Array Size
You may not always know the size of the array you are passed in a function
Java provides a data field built into every array to tell you how many elements are stored in it
arrayname.length will return the number of elements stored in the array
Cloning an Array
Sometimes you may need to copy an array for one reason or another
Java provides a function to make this easier
int newarray[] = (int []) oldarray.clone();
Simply copies all the elements of the old array into the new array
Arrays are the same size
Copying part of an array
To copy part of an array from one array to another, use the System.arraycopy() function
Syntax:
System.arraycopy(source_array, offset, dest_array, offset, length)
Will not work for multidimensional arrays, only for single arrays
Creation of a Project in Codewarrior
Demonstration of how to create a project in Codewarrior
Discussion of New Lab
Demo and discussion of Lab assigned for this week