0% found this document useful (0 votes)
32 views

Introducing Arrays: Array Is A Data Structure That Represents A Collection of The Same Data Type of Data

The document introduces arrays and how they can be used to store a collection of data of the same type. Key points: - Arrays allow storing multiple values of the same type through indexed variables. - Arrays are created with a size that cannot change, and elements are accessed via indexes from 0 to length-1. - Elements are initialized to default values like 0 for numbers unless initialized differently. - Arrays can be declared, created, and initialized in one statement using array initializers.

Uploaded by

Khoa Nguyễn
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Introducing Arrays: Array Is A Data Structure That Represents A Collection of The Same Data Type of Data

The document introduces arrays and how they can be used to store a collection of data of the same type. Key points: - Arrays allow storing multiple values of the same type through indexed variables. - Arrays are created with a size that cannot change, and elements are accessed via indexes from 0 to length-1. - Elements are initialized to default values like 0 for numbers unless initialized differently. - Arrays can be declared, created, and initialized in one statement using array initializers.

Uploaded by

Khoa Nguyễn
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 82

Introducing Arrays

Array is a data structure that represents a collection of the same data


type of data.

double[] myArray = new


double[10];
myArray reference
myArray[0] 5.6
myArray[1] 4.5
Array reference myArray[2] 3.3
variable
myArray[3] 13.2

myArray[4] 4
Array element at
myArray[5] 34.33 Element value
index 5
myArray[6] 34

myArray[7] 45.45

myArray[8] 99.993

myArray[9] 11123
Declaring Array Variables

• datatype[] arrayRefVar;
Example:
double[] myArray;

• datatype arrayRefVar[]; // This style is allowed, but not


preferred
Example:
double myArray[];
Creating Arrays

arrayRefVar = new datatype[arraySize];

Example:
myArray = new double[10];

myArray[0] references the first element in the array.


myArray[9] references the last element in the array.
Declaring and Creating in One Step

• datatype[] arrayRefVar = new


datatype[arraySize];

double[] myArray = new double[10];

• datatype arrayRefVar[] = new


datatype[arraySize];

double myArray[] = new double[10];


The Length of an Array

Once an array is created, its size is fixed. It cannot be


changed. You can find its size using

arrayRefVar.length

For example,

myArray.length returns 10
Default Values

When an array is created, its elements are assigned the


default value of

– 0 for the numeric primitive data types,


– '\u0000' for char types, and
– false for boolean types.
Indexed Variables

The array elements are accessed through the index. The array indices
are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In the
previous example, myArray holds ten double values and the indices
are from 0 to 9.

Each element in the array is represented using the following syntax,


known as an indexed variable:

arrayRefVar[index];
Using Indexed Variables

After an array is created, an indexed variable can be used in


the same way as a regular variable. For example, the
following code adds the value in myArray[0] and
myArray[1] to myArray[2].

myArray[2] = myArray[0] + myArray[1];


Array Initializers

• Declaring, creating, initializing in one step:


double[] myArray = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one statement.


Declaring, creating, initializing
using the Shorthand Notation

double[] myArray = {1.9, 2.9, 3.4, 3.5};


This shorthand notation is equivalent to the following statements:
double[] myArray = new double[4];
myArray[0] = 1.9;
myArray[1] = 2.9;
myArray[2] = 3.4;
myArray[3] = 3.5;
CAUTION

Using the shorthand notation, you have to declare, create, and initialize the array all
in one statement. Splitting it would cause a syntax error. For example, the
following is wrong:

double[] myArray;
myArray = {1.9, 2.9, 3.4, 3.5};
Trace Program with Arrays

Declare array variable values, create an


array, and assign its reference to values

public class Test {


public static void main(String[] args) { After the array is created

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) { 1 0

values[i] = i + values[i-1]; 2 0

} 3 0

4 0
values[0] = values[1] + values[4];
}
}
Trace Program with Arrays

i becomes 1

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 0

2 0
}
3 0
values[0] = values[1] + values[4]; 0
4
}
}
Trace Program with Arrays

i (=1) is less than 5

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 0

} 2 0

3 0
values[0] = values[1] + values[4];
4 0
}
}
Trace Program with Arrays

After this line is executed, value[1] is 1

public class Test {


public static void main(String[] args) { After the first iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 0

} 3 0

0
values[0] = values[1] + values[4]; 4

}
}
Trace Program with Arrays

After i++, i becomes 2

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
After the first iteration
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0

1 1
}
2 0
values[0] = values[1] + values[4]; 0
3
} 4 0

}
Trace Program with Arrays

i (= 2) is less than 5
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
After the first iteration
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
0 0
} 1
1
values[0] = values[1] + values[4]; 2 0
} 3 0
} 4 0
Trace Program with Arrays

After this line is executed,


values[2] is 3 (2 + 1)
public class Test {
public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

} 3 0

4 0
values[0] = values[1] + values[4];
}
}
Trace Program with Arrays

After this, i becomes 3.

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

} 3 0

4 0
values[0] = values[1] + values[4];
}
}
Trace Program with Arrays

i (=3) is still less than 5.

public class Test {


After the second iteration
public static void main(String[] args) {
int[] values = new int[5]; 0 0
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

3 0
}
4 0
values[0] = values[1] + values[4];
}
}
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

public class Test {


After the third iteration
public static void main(String[] args) {
int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

3 6
}
4 0
values[0] = values[1] + values[4];
}
}
Trace Program with Arrays

After this, i becomes 4

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

} 3 6

0
values[0] = values[1] + values[4]; 4

}
}
Trace Program with Arrays
i (=4) is still less than 5

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

} 3 6

0
values[0] = values[1] + values[4]; 4

}
}
Trace Program with Arrays

After this, values[4] becomes 10 (4 + 6)

public class Test {


public static void main(String[] args) { After the fourth iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) { 1 1

values[i] = i + values[i-1]; 2 3

} 3 6

10
values[0] = values[1] + values[4]; 4

}
}
Trace Program with Arrays

After i++, i becomes 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) { After the fourth iteration

values[i] = i + values[i-1];
0 0
} 1 1

values[0] = values[1] + values[4]; 2 3

3 6
} 4 10

}
Trace Program with Arrays

i ( =5) < 5 is false. Exit the loop

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
After the fourth iteration
values[i] = i + values[i-1];
0 0
} 1 1

values[0] = values[1] + values[4]; 2 3

3 6
} 4 10

}
Trace Program with Arrays

After this line, values[0] is 11 (1 + 10)


public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 11

values[i] = i + values[i-1]; 1 1

} 2 3

6
values[0] = values[1] + values[4]; 3
10
} 4

}
Processing Arrays

See the examples in the text.


1. (Initializing arrays)
2. (Printing arrays)
3. (Summing all elements)
4. (Finding the largest element)
5. (Finding the smallest index of the largest element)
Example: Testing Arrays

• Objective: The program receives 6 numbers from the user, finds the
largest number and counts the occurrence of the largest number entered.
Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its
occurrence count is 4.
Example: Assigning Grades

• Objective: read student scores (int, 0-100), get the best score,
and then assign grades based on the following scheme (store
grades in another array):
–Grade is A if score is >= best–10;
–Grade is B if score is >= best–20;
–Grade is C if score is >= best–30;
–Grade is D if score is >= best–40;
–Grade is F otherwise.
Copying Arrays

Often, in a program, you need to duplicate an array or a part of an


array. In such cases you could attempt to use the assignment
statement (=), as follows:
array2 = array1;

Before the assignment After the assignment


array2 = array1; array2 = array1;

array1 array1
Contents Contents
of array1 of array1

array2 array2
Contents Contents
of array2 of array2
Garbage
Copying Arrays

• Copies the reference to the array


• Does not copy the values in the second array!

Before the assignment After the assignment


array2 = array1; array2 = array1;

array1 array1
Contents Contents
of array1 of array1

array2 array2
Contents Contents
of array2 of array2
Garbage
Copying Arrays (the values within the array)

Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];

for (int i = 0; i < sourceArray.length; i++)


targetArray[i] = sourceArray[i];
The array copy Utility

arraycopy(sourceArray, src_pos, targetArray,


tar_pos, length);

Example:
System.arraycopy(sourceArray, 0, targetArray, 0,
sourceArray.length);
Anonymous Array

The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});

creates an array using the following syntax:


new dataType[]{literal0, literal1, ...,
literalk};

There is no explicit reference variable for the array. Such array is


called an anonymous array.
Pass By Value

Java uses pass by value to pass parameters to a method. There are important
differences between passing a value of variables of primitive data types and
passing arrays.

• For a parameter of a primitive type value, the actual value is passed.


Changing the value of the local parameter inside the method does not affect
the value of the variable outside the method.

• For a parameter of an array type, the value of the parameter contains a


reference to an array; this reference is passed to the method. Any changes to
the array that occur inside the method body will affect the original array that
was passed as the argument.
Simple Example: modifying a variable and an array
value in a method
public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values

myMethod(x, y); // Invoke m with arguments x and y

System.out.println("x is " + x); // what is the output?


System.out.println("y[0] is " + y[0]); // what is the output?
}

public static void myMethod (int number, int[] numbers) {


number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}
Call Stack

Stack Heap
Space required for
method m
int[] numbers:reference
The arrays are
int number: 1 Array of stored in a
ten int heap.
Space required for the values is
main method stored here
int[] y: reference
int x: 1

When invoking myMethod(x, y), the values of x and y are passed to


number and numbers. Since y contains the reference value to the array,
numbers now contains the same reference value to the same array.
Heap

Stack Heap
Space required for
xMethod
int[] numbers:reference
The arrays are
int number: 1 Array of stored in a
ten int heap.
Space required for the values are
main method stored here
int[] y: reference
int x: 1

• The JVM stores the array in an area of memory, called heap,


which is used for dynamic memory allocation where blocks of
memory are allocated and freed in an arbitrary order.
• Heap vs Stack: http://www.journaldev.com/4098/java-heap-
memory-vs-stack-memory-difference
Example:
Passing Arrays as Arguments

• Demonstrate differences of passing primitive data type variables and


array variables.
– Compare
–public static void swap(int n1, int n2)
–public static void
swapFirstTwoInArray(int[] array)
public class TestPassArray {
/** Main method */
public static void main(String[] args) {
int[] a = {1, 2}; /** Swap two variables */
public static void swap(int n1,
int n2) {
// Swap elements using the swap method int temp = n1; n1 = n2;
System.out.println("Before invoking swap"); n2 = temp;
}
System.out.println("array is {" + a[0] + ", " +
a[1] + "}"); /** Swap the first two elements
swap(a[0], a[1]); in the array */
public static void
System.out.println("After invoking swap"); swapFirstTwoInArray(int[] array)
System.out.println("array is {" + a[0] + ", " + {
a[1] + "}"); // what is the output? int temp = array[0];
array[0] = array[1];
array[1] = temp;
// Swap elements using the swapFirstTwoInArray }
method }
System.out.println("Before invoking
swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " +
a[1] + "}");
swapFirstTwoInArray(a);
System.out.println("After invoking
swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " +
a[1] + "}"); // what is the output?
}
Example, cont.

Stack Heap Stack


Space required for the
Space required for the swapFirstTwoInArray
swap method method
n2: 2 int[] array reference
n1: 1

Space required for the Space required for the


main method main method
int[] a reference int[] a reference
a[1]: 2
a[0]: 1
Invoke swap(int n1, int n2). Invoke swapFirstTwoInArray(int[] array).
The primitive type values in The arrays are The reference value in a is passed to the
a[0] and a[1] are passed to the stored in a swapFirstTwoInArray method.
swap method. heap.
Returning an Array from a method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

int[] list1 = new int[]{1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1);
Trace the reverse Method
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

Declare result and create array


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 0 and j = 5
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (= 0) is less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 0 and j = 5
public static int[] reverse(int[] list) { Assign list[0] to result[5]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 1 and j


public static int[] reverse(int[] list) { becomes 4
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=1) is less than 6


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 1 and j = 4
public static int[] reverse(int[] list) { Assign list[1] to result[4]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 2 and


public static int[] reverse(int[] list) { j becomes 3
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=2) is still less than 6


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 2 and j = 3
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 3 and


public static int[] reverse(int[] list) { j becomes 2
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=3) is still less than 6


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 3 and j = 2
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 4 and


public static int[] reverse(int[] list) { j becomes 1
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=4) is still less than 6


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 4 and j = 1
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 5 and


public static int[] reverse(int[] list) { j becomes 0
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=5) is still less than 6


public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i = 5 and j = 0
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

After this, i becomes 6 and


public static int[] reverse(int[] list) { j becomes -1
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=6) < 6 is false. So exit


public static int[] reverse(int[] list) { the loop.
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

Return result
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1;


i < list.length; i++, j--) {
result[j] = list[i];
}

return result;
}

list 1 2 3 4 5 6

list2
result 6 5 4 3 2 1
Example: Counting Occurrence of Each Letter

• Generate 100 lowercase letters randomly and assign to an array of characters.


• Count the occurrence of each letter in the array.

(a) Executing (b) After exiting


createArray in Line 6 createArray in Line 6

Stack Heap Stack Heap

Space required for the


Array of 100 Array of 100
createArray method
characters characters
char[] chars: ref
Space required for the Space required for the
main method main method
char[] chars: ref char[] chars: ref
Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];
Declaring Variables of Two-dimensional Arrays
and Creating Two-dimensional Arrays

int[][] matrix = new int[10][10];


or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);

double[][] x;
Two-dimensional Array Illustration

0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3

1 1 1 4 5 6

2 2 7 2 7 8 9

3 3 3 10 11 12

4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};

matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3
Declaring, Creating, and Initializing
using Shorthand Notations

You can also use an array initializer to declare, create and initialize a two-dimensional array.
For example,

int[][] array = {
int[][] array = new int[4][3];
{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
Same as
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};
Lengths of Two-dimensional Arrays

int[][] x = new int[3][4];

x
x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4
x[0]
x[1] x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4

x[2]
x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4
x.length is 3
Lengths of Two-dimensional Arrays, cont.

int[][] array = {
array.length
{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
array[3].length
{10, 11, 12}
};

array[4].length ArrayIndexOutOfBoundsException
Example: Grading Multiple-Choice Test

• Objective: write a program


Students’ Answers to the Questions:
that grades multiple-choice
0 1 2 3 4 5 6 7 8 9 test.
Student 0 A B A C C D E E A D
Student 1 D B A B C A E E A D
Student 2 E D D A C B E E A D
Student 3 C B A E D C E E A D Key to the Questions:
Student 4 A B D C C D E E A D 0 1 2 3 4 5 6 7 8 9
Student 5 B B E C C D E E A D
Student 6 B B A C C D E E A D Key D B D C C D A E A D
Student 7 E B E C C D E E A D
Appendices

• Ragged arrays
• Computing Taxes Using Arrays
Ragged Arrays (Optional)

Each row in a two-dimensional array is itself an array. So, the rows can have different
lengths. Such an array is known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
matrix.length is 5
{4, 5},
matrix[0].length is 5
{5} matrix[1].length is 4
}; matrix[2].length is 3
matrix[3].length is 2
matrix[4].length is 1
Ragged Arrays, cont.

int[][] triangleArray = { 1 2 3 4 5
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, 1 2 3 4
{3, 4, 5},
{4, 5}, 1 2 3
{5}
}; 1 2
1 2
Example: Computing Taxes Using Arrays

Liting 5.4, “Computing Taxes with Methods,” simplified Listing 3.4,


“Computing Taxes.” Listing 5.4 can be further improved using arrays.
Rewrite Listing 3.1 using arrays to store tax rates and brackets.
Refine the table

10% 6000 12000 6000 10000


15% 27950 46700 23350 37450
27% 67700 112850 56425 96745

30% 141250 171950 85975 156600


307050 307050 153525 307050
35%
38.6%
Reorganize the table

6000 12000 6000 10000


27950 46700 23350 37450
67700 112850 56425 96745
141250 171950 85975 156600
307050 307050 153525 307050

Rotate

6000 27950 67700 141250 307050 Single filer


12000 46700 112850 171950 307050 Married jointly
6000 23350 56425 85975 153525
Married separately
10000 37450 96745 156600 307050
Head of household
Declare Two Arrays

6000 27950 67700 141250 307050 Single filer


12000 46700 112850 171950 307050 Married jointly
6000 23350 56425 85975 153525
Married separately
10000 37450 96745 156600 307050
Head of household

10% int[][] brackets = {


{6000, 27950, 67700, 141250, 307050}, // Single filer
15%
{12000, 46700, 112850, 171950, 307050}, // Married jointly
27% {6000, 23350, 56425, 85975, 153525}, // Married separately
30% {10000, 37450, 96700, 156600, 307050} // Head of household
};
35%
38.6%
double[] rates = {0.10, 0.15, 0.27, 0.30, 0.35, 0.386};
Multidimensional Arrays (Optional)

Occasionally, you will need to represent n-dimensional data structures. In Java,


you can create n-dimensional arrays for any integer n.

The way to declare two-dimensional array variables and create two-dimensional


arrays can be generalized to declare n-dimensional array variables and create n-
dimensional arrays for n >= 3. For example, the following syntax declares a three-
dimensional array variable scores, creates an array, and assigns its reference to
scores.

double[][][] scores = new double[10][5][2];


Example: Calculating Total Scores

• Objective: write a program that calculates the total score for students in a class. Suppose
the scores are stored in a three-dimensional array named scores. The first index in scores
refers to a student, the second refers to an exam, and the third refers to the part of the exam.
Suppose there are 7 students, 5 exams, and each exam has two parts--the multiple-choice
part and the programming part. So, scores[i][j][0] represents the score on the multiple-
choice part for the i’s student on the j’s exam. Your program displays the total score for
each student.

You might also like