What We Will Cover
Illuminations
Homework Questions?
Viewing WebCT Assignment Results and Solutions
Questions from last class?
VTEA Surveys
^ top
4.1: Arrays
Objectives
At the end of the lesson the student will be able to:
- Declare and allocate memory for arrays
- Write code to initialize arrays
- Use arrays with loops
|
^ top
4.1.1: About Arrays
Array: a single name for a collection of identically-typed data values
- Arrays are a type of data structure
-- a way to organize data
- An array is used to process a collection of data of the same type
- Why do we need arrays?
- Imagine keeping track of 5 test scores, or 100, or 1000 in memory
- How would you name all the variables?
- How would you process each of the variables?
- Arrays provide a convenient solution to these problems
- Entire array referred to by a single identifier
- Each element uniquely identified by an index number
For Example
- One-dimensional array is like single row of data in spreadsheet or table
score[0] |
score[1] |
score[2] |
score[3] |
score[4] |
| 90 |
95 |
87 |
89 |
98 |
- Top row shows the indices for an array named "
score"
- Individual items are referenced by the index (a.k.a. subscript)
- All the values are of the same type:
int
- Array length is 5
When to Use Arrays
- Use arrays for storing data which must be accessed in any order
- Arrays are a natural fit for loops, especially
for loops
^ top
4.1.2: Declaring and Allocating Arrays
- Consider an array named
score containing 5 values
- You declare and allocate memory for this array like this:
int[] score; // declaration
score = new int[5]; // allocation
Which is equivalent to:
int[] score = new int[5]; // Java style
Which is equivalent to:
int score[] = new int[5]; // C++ style
This is like declaring 5 variables of type int numbered as follows:
score[0], score[1], score[2], score[3], score[4]
The value in brackets is called an index or subscript
Individual values in an array are called items or elements
The number of indexed variables in an array is the size of the array
- The largest index is one less than the size
- The first index value is zero
Array declaration syntax:
DataType[] arrayName = new DataType[length];
Arrays can be of any data type
All the variables of an array are always of the same data type
- Known as the base type of the array
Allocated dynamically with operator new
Once created, you cannot change the number of elements
^ top
4.1.3: Referencing Array Elements
- Each array element is referenced by name and an index inside of square brackets
score[3] is one of the indexed variables of the score array
score[0]++;
The index can be any integer expression
int n = 2;
score[n + 1] = 99;
You can use an indexed array variable like any regular variable
score[0] = score[1] + 1;
- Array elements referenced by the array name and index
- Use the array operator
[] to specify the index
- Index must be an integer expression
^ top
4.1.4: Initializing Array Values
- You can assign a value to an array element any time after it is declared
int[] score = new int[5];
score[0] = 90;
score[1] = 95;
score[2] = 87;
score[3] = 89;
score[4] = 98;
Static Initialization
- You can also initialize array elements in the declaration statement
- Called static initialization
- Use a comma-separated list inside curly-braces
int[] score = {90, 95, 87, 89, 98};
Produces the same array
Length of an array automatically determined from the initializer list
Default Values
- Uninitialized array elements are assigned default values:
- Integer (
byte, short, int, long): 0
- Floating-point (
float, double): 0.0
- Character (
char): '\u0000'
- Boolean:
false
- Objects:
null
^ top
4.1.5: Processing Array Values in a Loop
- Array processing is easily done in a loop
- A
for loop is commonly used to process array elements
- For example, to initialize array elements to a known value:
double[] scores = new double[5];
for (int i = 0; i < scores.length; i++) {
scores[i] = 100;
}
Note the use of the constant length in the array loop
Displaying an Array
- Similarly, we can also use a loop to display the contents of an array
System.out.println("You entered:");
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
Initializing From the Keyboard
- We can also use a loop to initialize values from the keyboard
- This is shown in the example application below
- Note that the loop counter and array index counts from 0 to length - 1
Example Application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.util.Scanner;
public class ScoreReader {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your scores.\n"
+ "Number of scores: ");
int num = input.nextInt();
double[] scores = new double[num];
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter score "
+ (i + 1) + ": ");
scores[i] = input.nextDouble();
}
System.out.println("You entered:");
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
}
}
|
^ top
4.1.6: Array Index Out of Range
- A common error is using a nonexistent index
- Index values for int
score[5] are the values 0 through 4
- An index value not allowed by the array declaration is out of range
- Using an out of range index value produces an error message!
ArrayIndexOutOfBoundsException
For example, using the following code:
1
2
3
4
5
6
7
8
9
10
|
public class WeekDays {
public static void main(String[] args) {
String[] day = {"Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"};
for (int x = 0; x < day.length; x++) {
System.out.println(day[x]);
}
}
}
|
- Trying to use an index less than 0 or more than
length - 1 causes an error
ArrayIndexOutOfBoundsException
^ top
4.1.7: Summary
- Arrays are convenient ways to process a list of data
- You declare an array with a single statement:
DataType[] arrayName = new DataType[length];
Each array element is referenced by name and an index inside of square brackets
You can use an indexed array variable like any regular variable
score[0] = score[1] + 1;
You can initialize array elements individually with an assignment statement
score[0] = 90;
A more convenient way is to use an initializer list
int score[] = {90, 95, 87, 89, 98};
You can use loops to assign values to an array and to display array values
The programmer must be very careful to keep the array index within bounds
Otherwise an error message will result
ArrayIndexOutOfBoundsException
^ top
Exercise 4.1
Take one minute to prepare an answer the following questions.
- Is it possible to create arrays of length zero?
- Given the following declaration, which statement is valid?
int[] array = new int[5];
System.out.print(array[].length);
System.out.print(array.length());
System.out.print(array[].length());
System.out.print(array.length);
System.out.print(array.size);
^ top
4.2: Arrays and Methods
Objectives
At the end of the lesson the student will be able to:
- Pass arrays elements as arguments
- Pass entire arrays as arguments
- Use arrays in methods
- Return arrays from methods
- Obtain values from the array passed to the
main method
|
^ top
4.2.1: Array Elements as Arguments
- Indexed variables can be arguments to methods
- For example, if a program contains these declarations:
public static void main(String[] args) {
int i = 0, a[] = new int[10];
}
static void myMethod(int n) { /* some code */ }
You can use indexed variables a[0] through a[9] as arguments
myMethod(a[0]);
myMethod(a[3]);
myMethod(a[i]);
For Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import java.text.NumberFormat;
public class ArrayItemApp {
public static void main(String[] args) {
double[] data = {12.3, 23.45, 3.456};
for (int i = 0; i < data.length; i++) {
showPrice(data[i]);
}
}
/**
* Displays a double to the screen
*/
static void showPrice(double value) {
NumberFormat currency =
NumberFormat.getCurrencyInstance();
String formattedItem = currency.format(value);
System.out.println(formattedItem);
}
}
|
^ top
4.2.2: Arrays as Method Parameters
- You can use an entire array as an argument to a method
- When calling the array, use just the array name and no brackets
showArray(days);
Method has access to the original array
Following example shows an array used in a method:
static void showArray(String[] values) {
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
You do not know the length of the array that will be passed
Length of the array passed can be different for each method call
So use the length variable inside the method body
You could easily overload the showArray method for different array types
^ top
4.2.3: Changing Array Elements in Methods
- All types in Java are passed-by-value (a.k.a. call-by-value)
- When method is called, value of each argument is copied to its corresponding parameter
- Method only gets a copy of the variable's value
- Variables used as arguments cannot be changed within the method
- However, arrays are objects and a variable contains reference values
- Location of the array is passed to the method
- Any action taken on the parameter is actually taken on the original argument
- Original argument is not protected for class types
- Thus array elements can be changed in methods
- You can even collect input in a method for an array

For Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import java.util.Scanner;
class ArrayInput {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many items? ");
int numItems = input.nextInt();
int[] data = new int[numItems];
fillUp(data);
showArray(data);
}
// Fills an array with values from the keyboard
static void fillUp(int data[]) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < data.length; i++) {
System.out.print("Enter number " + (i + 1)
+ ": ");
data[i] = (int) input.nextDouble();
}
}
// Displays an array to the screen
static void showArray(int[] values) {
System.out.println("You entered " + values.length
+ " numbers:");
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
}
|
^ top
4.2.4: Returning an Array
- Methods can return an array reference
- Local array name just another name for the original array
- For example:
1
2
3
4
5
6
7
8
9
10
11
12
|
public class ArrayMaker {
public static void main(String arg[]) {
char[] c = makeVowelsArray();
for(int i = 0; i < c.length; i++)
System.out.println(c[i]);
}
static char[] makeVowelsArray() {
char[] vowelArray = {'a', 'e', 'i', 'o', 'u'};
return vowelArray;
}
}
|
^ top
4.2.5: Method main Parameters
public static void main(String[] args) {
Recall that every Java application must have a method called main
- Applications begin executing at
main method
Notice that the parameter args is an array of Strings
Arguments are passed to the program by the operating system
All words after the class name passed in the args array
java ArgEcho Java Rules!
Number of parameters can be determined from args.length
System.out.println(args.length);
args is a parameter of type String[]
Parameter String[] is an array of Strings
Parameters are passed when calling the program
Name args is a convention -- can be named anything
Number of parameters can be determined from the length field of args
For Example
1
2
3
4
5
6
7
8
|
public class ArgEcho {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.print("Arg " + i + ": ");
System.out.println(args[i]);
}
}
}
|
>java EchoArgs Hi Mom!
Arg 0: Hi
Arg 1: Mom!
^ top
4.2.6: Summary
- You can pass an array to a method
- A method may return an array
- Can change the array element within a method body
- Because arrays are reference types
- Location of the array passed to the method
- When an element is accessed, the original location is used
- Operating system sends arguments to the
String[] parameter of method main
- Can access these elements like any other array
^ top
Exercise 4.2
Take one minute to prepare an answer the following question:
- What is wrong with the following method definition?
public void doubleSize(int[] a) {
a = new int[a.length * 2];
}
- An array length must be a literal integer and cannot be created from a calculated expression.
- The length of the array
a is unknown when declaring the new array.
- Parameter
a already has an array assigned and you cannot assign a new value to parameter a.
- The code is useless because parameter
a goes out of scope when the method returns.
^ top
4.3: Programming With Arrays
Objectives
At the end of the lesson the student will be able to:
- Test array equality
- Compute statistics on arrays of data
- Search an array
- Sort an array
- Choose the best algorithm for searching an array
|
^ top
4.3.1: Using Arrays Interactively
Run-Time Dimensioning
- An entered value can be used to allocate space for an array
- Size of an array is known as its dimension
- Sizing an array at run time is referred to as run-time dimensioning
Example
For Example
- Consider the case of reading user input into an array
- Note that there is no automatic mechanism to detect how many items have been entered
- Programmer must keep track of the progress
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import java.util.Scanner;
class ArrayInput {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many items? ");
int numItems = input.nextInt();
int[] data = new int[numItems];
fillUp(data);
showArray(data);
}
// Fills an array with values from the keyboard
static void fillUp(int data[]) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < data.length; i++) {
System.out.print("Enter number " + (i + 1)
+ ": ");
data[i] = (int) input.nextDouble();
}
}
// Displays an array to the screen
static void showArray(int[] values) {
System.out.println("You entered " + values.length
+ " numbers:");
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
}
|
Check Yourself
- When is the size of the array decided?
- What does the
data array contain before the user enters any values?
- What is the value of
data.length after one item has been entered?
- How do we know how many items have been entered by the user?
^ top
4.3.2: Testing Array Equality
Using == With Array Names
- Remember that arrays are objects
- Thus, array variables are reference types

- Tests using
== checks if the memory addresses are the same
if (a == b)
For example, what does the following code print?
1
2
3
4
5
6
7
8
9
10
11
|
public class ArrayChecker {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
if (a == b) {
System.out.println("a == b");
} else {
System.out.println("a != b");
}
}
}
|
- Both arrays have the same elements
- However, they are stored at different locations in memory
- Thus, they do not have the same memory address
Testing Array Elements for Equality
- To test array elements for equality, need to check each element
- Define an equals method that returns true if and only if all the array elements are equal
- Arrays must also be the same length
- Updating our original code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class ArrayTester {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
if (a == b) {
System.out.println("a == b");
} else {
System.out.println("a != b");
}
if (equals(a, b) == true) {
System.out.println("a equals b: ");
} else {
System.out.println("a not equal to b");
}
}
public static boolean equals(int[] a, int[] b) {
boolean match = true; //tentatively
if (a.length != b.length) {
match = false;
} else {
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) match = false;
}
}
return match;
}
}
|
^ top
4.3.3: Calculating Statistics on Arrays
- Can use a loop to access every item in an array
1
2
3
4
5
6
7
8
9
10
11
|
public class ArraySum {
public static void main(String [] args) {
int[] data = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
System.out.print(data[i] + ", ");
}
System.out.println("\nsum = " + sum);
}
}
|
- What code would we add to show the average of the array values?
- What would we change to find the maximum array value?
- How would we find the minimum array value?
- What is the easiest way to initialize minimum and maximum values?
Restricting the Range
- We can choose to calculate statistics over a portion of an array
- For example, the following finds a minimum between
start and end
- Note that it does not return a value, but rather an array index
- You use the array index to look up the minimum value
static int findMin(int[] data, int start, int end) {
int indexOfMin = start;
for (int i = start + 1; i <= end; i++) {
if (data[i] < data[indexOfMin]) {
indexOfMin = i;
}
}
return indexOfMin;
}
^ top
4.3.4: Searching an Array
- Searching an array is about finding the index where a value is store
- Many techniques for searching an array for a particular value
- Easiest technique is sequentional search, whose algorithm is:
- Start at the beginning of the array
- Compare each value in sequence
- If value is found, then return the index
- Continue until you reach the end of the array
- If no match is found, return -1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class Array9Finder {
public static void main(String [] args) {
int[] data = {12, -3, 9, -5, 10};
final int valueToFind = 9;
boolean found = false;
int count = 0;
while ((!found) && (count < data.length)) {
if (valueToFind == data[count]) {
found = true;
}
count++;
}
if (found) {
System.out.print("Found ");
} else {
System.out.print("Did not find ");
}
System.out.println(valueToFind + " in "
+ count + " comparisons");
}
}
|
- Would it be any faster to start searching at the end of an array?
- If an array is sorted, then we can program faster methods -- binary search
^ top
4.3.5: Sorting an Array
- Sorting is a common task for computers, for example:
- Sort numbers in ascending order
- Sort numbers in descending order
- Sort strings in alphabetic order
- Many different algorithms for sorting, including:
- Bubble sort - move item up until in right place
- Insertion sort - add elements to list one at a time
- Selection sort - pick 1st, then 2nd, etc.
- Quick sort - divide and conquer
Selection Sort
- Selection sort is one of the easiest -- but not the most efficient
- General algorithm:
- Find the smallest element
- Swap with the first element
- Find the smallest element in the rest of the list
- Swap with the first element of the rest of the list
- Repeat until the list is sorted
| Pass |
a[0] |
a[1] |
a[2] |
a[3] |
a[4] |
a[5] |
a[6] |
| Original |
10 |
7 |
29 |
14 |
-4 |
-12 |
21 |
| First |
-12 |
7 |
29 |
14 |
-4 |
10 |
21 |
| Second |
-12 |
-4 |
29 |
14 |
7 |
10 |
21 |
| Third |
-12 |
-4 |
7 |
14 |
29 |
10 |
21 |
| Fourth |
-12 |
-4 |
7 |
10 |
29 |
14 |
21 |
| Fifth |
-12 |
-4 |
7 |
10 |
14 |
29 |
21 |
| Sixth |
-12 |
-4 |
7 |
10 |
14 |
21 |
29 |
- How many passes were needed for a seven element array?
Selection Sort Code
- Following is selection sort code
- Have added some statements to show action for each pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
public class SelectionSort {
public static void main(String [] args) {
int[] a = {10, 7, 29, 14, -4, -12, 21};
System.out.print("Original array: ");
showArray(a);
sort(a);
System.out.print("\nSorted array: ");
showArray(a);
}
public static void showArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ", ");
}
System.out.println();
}
static void sort(int[] a) {
int index, indexOfMin;
for (index = 0; index < a.length - 1; index++) {
indexOfMin = findMin(a, index, a.length - 1);
swap(a, index, indexOfMin);
System.out.print("Pass#" + index + ": ");
showArray(a);
}
}
static int findMin(int[] a, int start, int end) {
int indexOfMin = start;
for (int i = start + 1; i <= end; i++) {
if (a[i] < a[indexOfMin]) {
indexOfMin = i;
}
}
return indexOfMin;
}
static void swap(int[] a, int first, int second) {
System.out.println("\nSwapping " + a[first]
+ " with " + a[second]);
int temp = a[first];
a[first] = a[second];
a[second] = temp;
}
}
|
- Note that every element in the array must have a value
- Can the array have duplicate items?
- Also note that the larger task was broken into smaller tasks using methods
- Helps to organize program and improve clarity
What About Bubble Sort?
- Another sorting algorithm that is easy to understand and use
- General algorithm:
- Make
array.length passes through the array
- For each pass, compare each array element with the next element
- If the current element is larger than the next one, swap them
- Not an efficient sorting algorithm
- Sometimes simple algorithms perform poorly
- Simple algorithms still useful because: easy to program and understand
- If better performance is needed, can replace with a better algorithm
- More information: Sorting Algorithms
- Includes Java source code
^ top
4.3.6: Binary Search
- Once an array is sorted, can use binary search to find an item
- Binary search is much faster than sequential search
Binary Search Algorithm
- A key value is searched for among the values stored in the array.
- Two index variables
lowIdx and highIdx are used to limit the scope of the search.
- The search proceeds until the element searched for is found or the scope between
lowIdx and highIdx is exhausted.
- The index
middleIdx is computed as
(lowIdx + highIdx) / 2.
- If
key = data[middleIdx] the search is successful.
- If
key < data[middleIdx], highIdx is lowered to middleIdx.
If key > data[middleIdx], lowIdx is raised to middleIdx.
- If the scope between
lowIdx and highIdx is exhausted, the search is unsuccessful.
- Demonstration applet: BinarySearch
Binary Search Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
public class BinarySearch {
public static void main(String [] args) {
int[] a = {-12, -4, 7, 10, 14, 21, 29};
int key = 14;
System.out.print("Searching array: ");
showArray(a);
int index = binarySearch(a, key);
System.out.println("Index of " + key
+ " = " + index);
}
static void showArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ", ");
}
System.out.println();
}
// find the index of key in array a
// return -1 if key is not found
static int binarySearch(int[] a, int key) {
int step = 0;
int lowIdx = 0;
int highIdx = a.length - 1;
int middleIdx;
while (lowIdx <= highIdx) {
step++;
middleIdx = (lowIdx + highIdx) / 2;
System.out.println("Step#" + step
+ " lowIdx=" + lowIdx
+ " highIdx=" + highIdx
+ " middleIdx=" + middleIdx);
if (a[middleIdx] == key) {
return middleIdx; // just right
} else if (a[middleIdx] < key) {
lowIdx = middleIdx + 1; // too small
} else {
highIdx = middleIdx - 1; // too big
}
}
return -1; // not found
}
}
|
How Much Faster is Binary Search?
- Given the sorted array:
| a[0] |
a[1] |
a[2] |
a[3] |
a[4] |
a[5] |
a[6] |
| -12 |
-4 |
7 |
10 |
14 |
21 |
29 |
- How many steps to find the value of 14 using sequential search?
- How many steps to find the value of 14 using binary search?
- On average for an array of n elements:
- Sequential search takes n / 2 steps
- Binary search takes 2 * log2(n) + 2 steps maximum
- Translating to some array sizes:
| Array Size |
floor(log2(n)) + 1 |
| 1 |
1 |
| 10 |
4 |
| 100 |
7 |
| 1000 |
10 |
| 10,000 |
14 |
- Binary search quickly becomes worth the effort of its implementation
- Binary search is one algorithm a programming professional should know!
^ top
4.3.7: Summary
- Arrays can be dimensioned at run time
- You can easily enter values into an array for later processing
- Arrays work well with loops to sum data and calculate other statistics
- Can search arrays sequentially to find a value
- Sorting algorithms can sort an array into ascending or descending order
- If an array is sorted, can use binary search to speed the search process
^ top
Exercise 4.3
Take one minute to prepare an answer the following question:
- What would be the contents of the following array after each pass of SelectionSort?
int[] array = {9, 21, -7, 2, 87, -19, 47}
^ top
4.4: Multidimensional Arrays
Objectives
At the end of the lesson the student will be able to:
- Use two-dimensional (2D) arrays
- Apply the techniques of 2D arrays to higher dimensions
|
^ top
4.4.1: Introducing Multidimensional Arrays
- Arrays in Java are objects
- Array elements can be objects, such as
Strings
- Thus, array elements can reference other arrays
- This allows Java to have arrays of multiple dimensions
String[] one;
double[][] two;
char[][][] three;
Each added dimension requires one more pair of square braces
We will focus on two-dimensional (2D) arrays in this section
You then use similar techniques for multidimensional arrays
Rows and Columns
- Two-dimensional (2D) arrays are like a spreadsheet or table
- First dimension is the row
- Second dimension is the column
- Array elements are the intersection of a row and column
- For the array named
data:
data[0][0] |
data[0][1] |
data[0][2] |
data[1][0] |
data[1][1] |
data[1][2] |
^ top
4.4.2: Declaring and Allocating 2D Arrays
- To declare as a 2D int-array:
int[][] data;
or
int data[][];
or even
int[] data[];
You can allocate 2D arrays dynamically
int data[][]; // C-style
data = new int[2][3];
or
int[][] data = new int[2][3];
or
int[][] data = new int[2][];
data[0] = new int[3];
data[1] = new int[3];
^ top
4.4.3: Initializing 2D Arrays
- Like one-dimensional arrays, 2D array elements are assigned default values based on the array type:
- Integer (
byte, short, int, long): 0
- Floating-point (
float, double): 0.0
- Character (
char): '\u0000'
- Boolean:
false
- Objects:
null
- You can initialize 2D arrays with static initializers or loops
- For example: 2 row by 3 column array using static initializers:
int[][] data = {{1,2,3}, {4,5,6}};
Can process multi-D arrays by nesting loops
Each loop has its own counter that corresponds to an index
1
2
3
4
5
6
7
8
9
10
11
12
|
public class TwoD {
public static void main(String[] args) {
int[][] data = {{1, 2, 3}, {2, 4, 6}};
for (int i = 0; i < data.length; i++) {
System.out.print("Row " + i + ": ");
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + ", ");
}
System.out.println();
}
}
}
|
Row 0: 1, 2, 3,
Row 1: 2, 4, 6,
^ top
4.4.4: Example: Creating a Table
- Methods may have multi-D array parameters
- Methods may return a multi-D array as the value returned
- Similar to 1D arrays, but with more brackets
- Example: 2D int array of the multiplication table
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class MultTable {
public static void main(String[] args) {
int[][] table = makeTable(9);
showTable(table);
}
static int[][] makeTable(int size) {
int[][] table = new int[size][size];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = (i + 1) * (j + 1);
}
}
return table;
}
static void showTable(int[][] table) {
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] < 10) {
System.out.print(" ");
}
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
|
Notes on the Code
static int[][] makeTable(int size) {
Method makeTable returns a 2D table
static void showTable(int[][] table) {
Method showTable takes a 2D int array as a parameter
^ top
4.4.5: Ragged Arrays
- Ragged arrays have rows of unequal length
- Rows can have arrays assigned of different lengths
- Produces rows with different numbers of columns
- For example:
int data[][];
data = new int[3][]; // allocate columns
data[0] = new int[5]; // allocate row 0
data[1] = new int[0]; // allocate row 1
data[2] = new int[3]; // allocate row 2
Can also use static initialization and get the same result
int[][] data = {{1,2,3,4,5}, {}, {6,7,8}};
^ top
4.4.6: Summary
- Arrays can have more than one index
- Each index is called a dimension
- Thus, multidimensional arrays have multiple indexes,
- For example, an array with two indexes is a two-dimensional array.
- 2D array can be thought of as a grid or table with rows and columns:
- One index is for the row, the other for the column.
- Multi-dimensional arrays in Java are implemented as arrays of arrays,
- 2D array is a 1D array of 1D arrays.
^ top
Exercise 4.4
Take one minute to prepare an answer the following question:
- Which one of the following 2D array declarations and initializations is not valid?
int[] a[] = {{1, 2}, {1}, {}, {1, 2, 3, 4}};
int b[] = new int[2] {1, 2};
int[] c = new int[] {1, 0, 2, 3};
int d[] = new int[] {1, 2};
int e[][] = {{1,2}, new int[2]};
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: March 19 2005 @19:47:02
|