28/08/2024 1
Arrays in Java
Jasmine Beulah Gnanadurai, PhD
28/08/2024 2
Opening Problem
Read one hundred numbers, compute their average, and
find out how many numbers are above the average.
28/08/2024 3
Introducing Arrays
Array is a data structure that represents a collection of the same types
of data.
28/08/2024 4
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
• datatype arrayRefVar[]; // This style is allowed, but not preferred
Example:
double myList[];
28/08/2024 5
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
28/08/2024 6
Declaring and Creating in One Step
• datatype[] arrayRefVar = new datatype[arraySize];
double[] myList = new double[10];
• datatype arrayRefVar[] = new datatype[arraySize];
double myList[] = new double[10];
28/08/2024 7
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,
myList.length returns 10
28/08/2024 8
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 example, myList 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];
28/08/2024 9
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 myList[0] and
myList[1] to myList[2].
myList[2] = myList[0] + myList[1];
28/08/2024 10
Array Initializers
• Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one statement.
28/08/2024 11
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
28/08/2024 12
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[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
13
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line is executed, value[1] is 1
After the first iteration
0
1
2
3
4
0
1
0
0
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
14
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After i++, i becomes 2
After the first iteration
0
1
2
3
4
0
1
0
0
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
15
Trace Program with Arrays
public class Test {
public static void main(String[]
args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] +
values[4];
}
}
i (= 2) is less than 5
After the first iteration
0
1
2
3
4
0
1
0
0
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
16
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line is executed,
values[2] is 3 (2 + 1)
After the second iteration
0
1
2
3
4
0
1
3
0
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
17
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, i becomes 3.
After the second iteration
0
1
2
3
4
0
1
3
0
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
18
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=3) is still less than 5.
After the second iteration
0
1
2
3
4
0
1
3
0
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
19
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line, values[3] becomes 6 (3 + 3)
After the third iteration
0
1
2
3
4
0
1
3
6
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
20
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, i becomes 4
After the third iteration
0
1
2
3
4
0
1
3
6
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
21
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=4) is still less than 5
After the third iteration
0
1
2
3
4
0
1
3
6
0
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
22
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, values[4] becomes 10 (4 + 6)
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
23
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After i++, i becomes 5
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
24
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i ( =5) < 5 is false. Exit the loop
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
28/08/2024
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
25
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line, values[0] is 11 (1 + 10)
0
1
2
3
4
11
1
3
6
10
28/08/2024
28/08/2024 26
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
28/08/2024 27
Initializing arrays with random values
for (int i = 0; i < myList.length; i++) {
myList[i] = Math.random() * 100;
}
28/08/2024 28
Printing arrays
for (int i = 0; i < myList.length; i++) {
System.out.print(myList[i] + " ");
}
28/08/2024 29
Summing all the elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
28/08/2024 30
Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++)
{
if (myList[i] > max)
max = myList[i];
}
28/08/2024 31
Random Shuffle
28/08/2024 32
Shifting Elements
28/08/2024 33
Enhanced for Loop (for-each loop)
for loop that enables you to traverse the complete array sequentially without using an
index variable. For example, the following code displays all elements in the array myList:
for (double value: myList)
System.out.println(value);
In general, the syntax is
for (elementType value: arrayRefVar) {
// Process the value
}
You still have to use an index variable if you wish to traverse the array in a different
order or change the elements in the array.
28/08/2024 34
Self-check
Write an enhanced for loop that prints all elements in the array
values.
Answer:
for (double x:values)
{
System.out.println(x);
}
28/08/2024 35
Read one hundred numbers, compute their average, and
find out how many numbers are above the average.
int n1, n2,…, n100;
Scanner input = new Scanner(System.in);
n1 = input.nextInput();
n2 = input.nextInput();
n3 = input.nextInput();
.....
n100 = input.nextInput();
28/08/2024 36
Solution through Arrays
int [] n = new int[100];
Scanner input = new Scanner(System.in);
for (int i=0; i < 100; i++)
{
n[i] = input.nextInt();
}
28/08/2024 37
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:
list2 = list1;
28/08/2024 38
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];
28/08/2024 39
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Invoke the method
int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
Invoke the method
printArray(new int[]{3, 1, 2, 6, 4, 2});
Anonymous array
28/08/2024 40
Searching Arrays
Searching is the process of looking for a specific element in an array;
for example, discovering whether a certain score is included in a list of scores.
Searching is a common task in computer programming.
There are many algorithms and data structures devoted to searching.
In this section, two commonly used approaches are discussed, linear search and
binary search.
public class LinearSearch {
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}
}
list
key Compare key with list[i] for i = 0, 1, …
[0] [1] [2] …
41
Linear Search Animation
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
3
3
3
3
3
3
Key List
28/08/2024
42
Binary Search
28/08/2024
For binary search to work, the elements in the array must already be ordered.
Without loss of generality, assume that the array is in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with the element in the middle of
the array.
43
Binary Search, cont.
28/08/2024
• If the key is less than the middle element, you only need to search the
key in the first half of the array.
• If the key is equal to the middle element, the search ends with a match.
• If the key is greater than the middle element, you only need to search the
key in the second half of the array.
Consider the following three cases:
28/08/2024 44
Binary Search
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
8
8
8
Key List
28/08/2024 45
Binary Search
28/08/2024 46
Binary Search
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
2 4 7 10 11 45 50 59 60 66 69 70 79
key is 54
key > 50
list
mid
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66
key < 59
high
low
mid high
low
list
[7] [8]
mid high
low
list
59 60 66 69 70 79
59 60
[6] [7] [8]
high
low
59 60
28/08/2024 47
Binary Search
The binarySearch method returns the index of the element in the list that
matches the search key if it is contained in the list. Otherwise, it returns
-insertion point - 1.
The insertion point is the point at which the key would be inserted into the
list.
28/08/2024 48
2D Array Declaration and Creation
 2D arrays are used to store a matrix or a table
Declaring Array Variables
elementType[][] arrayRefVar;
e.g. int[][] matrix;
 Declaration of an array variable does not allocate any space in
memory for the array
Creating Arrays
arrayRefVar = new elementType[rowSize][columnsize];
e.g. int[][] matrix = new int[5][5];
28/08/2024 49
2D Array Declaration and Creation
Assigning Value to elements
arrayRefVar[index2][index2] = value;
e.g. matrix[2][1] = 7;
28/08/2024 50
Array Size
 A two-dimensional array is actually an array in which each element
is a one-dimensional array
 If x = new int[3][4] then x[0], x[1], and x[2] are one-dimensional
arrays and each contains four elements
28/08/2024 51
Initializing and Processing 2D Arrays
28/08/2024 52
Some Examples of Processing 2D Arrays
 Initializing arrays with input values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = input.nextInt();
}
}
 Initializing arrays with random values
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}
 Displaying arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
28/08/2024 53
Multi Dimensional Arrays
 n-dimensional Array means collection of (n-1)-dimensional Arrays
 The way to declare two-dimensional array variables and create two-dimensional
arrays can be generalized to declare n-dimensional array variables
 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];
28/08/2024 54
ArrayList
 Useful class for storing objects
 Arrays can be used to store objects but once the array is created, its size is fixed.
 Java provides the ArrayList class that can be used to store an unlimited number
of objects
 ArrayList supports dynamic arrays
 Defined in java.util package
28/08/2024 55
ArrayList
 Constructors of ArrayList class are
ArrayList() : creates an empty array list with an initial capacity sufficient to
hold 10 elements.
e.g. ArrayList list =new ArrayList();
ArrayList(int capacity) : creates an array list that has the specified initial
capacity.
e.g. ArrayList list =new ArrayList(20);
ArrayList(Collection c) : creates an array list that is initialized with the
elements of the collection c.
e.g. ArrayList l = new ArrayList(list);
Array lists are created with an initial size. When this size is exceeded, the
collection is automatically enlarged
28/08/2024 56
Methods of ArrayList
1. void add(int index, Object element)
 Inserts the specified element at the specified position index in this list.
 Throws IndexOutOfBoundsException if the specified index is is out of range.
2. boolean add(Object o)
 Appends the specified element to the end of this list.
3. boolean addAll(Collection c )
 Appends all of the elements in the specified collection to the end of this list.
 Throws NullPointerException if the specified collection is null.
4. boolean addAll(int index, Collection c )
 Inserts all of the elements of the specified collection into this list, starting at the
specified position.
 Throws NullPointerException if the specified collection is null.
28/08/2024 57
Methods of ArrayList
5. void clear() : Removes all of the elements from this list.
6. Object remove(int index) : Removes the element at the specified position in
this list.
7. Object clone() : Returns a shallow copy of this ArrayList.
8. int size(): Returns the number of elements in the list.
9. boolean contains(Object o): Returns true if this list contains the specified
element.
28/08/2024 58
Methods of ArrayList
10. Object get(int index): Returns the element at the specified position in this list.
11. Object set(int index, o Object): Sets the element at the specified index.
12. int indexOf(Object o): Returns the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain the element.
13. int lastIndexOf(Object o):Returns the index in this list of the last occurrence of the
specified element, or -1.
14. void ensureCapacity(int minCapacity) : Increases the capacity of this ArrayList
instance, if necessary, to ensure that it can hold at least the number of elements specified by the
minimum capacity argument.
28/08/2024 59
Arrays vs ArrayList
28/08/2024 60

Arrays and Detailed explanation of Array

  • 1.
    28/08/2024 1 Arrays inJava Jasmine Beulah Gnanadurai, PhD
  • 2.
    28/08/2024 2 Opening Problem Readone hundred numbers, compute their average, and find out how many numbers are above the average.
  • 3.
    28/08/2024 3 Introducing Arrays Arrayis a data structure that represents a collection of the same types of data.
  • 4.
    28/08/2024 4 Declaring ArrayVariables • datatype[] arrayRefVar; Example: double[] myList; • datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];
  • 5.
    28/08/2024 5 Creating Arrays arrayRefVar= new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.
  • 6.
    28/08/2024 6 Declaring andCreating in One Step • datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; • datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10];
  • 7.
    28/08/2024 7 The Lengthof 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, myList.length returns 10
  • 8.
    28/08/2024 8 Indexed Variables Thearray elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length- 1. In the example, myList 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];
  • 9.
    28/08/2024 9 Using IndexedVariables 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 myList[0] and myList[1] to myList[2]. myList[2] = myList[0] + myList[1];
  • 10.
    28/08/2024 10 Array Initializers •Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
  • 11.
    28/08/2024 11 Declaring, creating,initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
  • 12.
    28/08/2024 12 CAUTION Using theshorthand 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[] myList; myList = {1.9, 2.9, 3.4, 3.5};
  • 13.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 13 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, value[1] is 1 After the first iteration 0 1 2 3 4 0 1 0 0 0 28/08/2024
  • 14.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 14 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 2 After the first iteration 0 1 2 3 4 0 1 0 0 0 28/08/2024
  • 15.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 15 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (= 2) is less than 5 After the first iteration 0 1 2 3 4 0 1 0 0 0 28/08/2024
  • 16.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 16 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, values[2] is 3 (2 + 1) After the second iteration 0 1 2 3 4 0 1 3 0 0 28/08/2024
  • 17.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 17 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 3. After the second iteration 0 1 2 3 4 0 1 3 0 0 28/08/2024
  • 18.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 18 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=3) is still less than 5. After the second iteration 0 1 2 3 4 0 1 3 0 0 28/08/2024
  • 19.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 19 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[3] becomes 6 (3 + 3) After the third iteration 0 1 2 3 4 0 1 3 6 0 28/08/2024
  • 20.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 20 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 4 After the third iteration 0 1 2 3 4 0 1 3 6 0 28/08/2024
  • 21.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 21 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=4) is still less than 5 After the third iteration 0 1 2 3 4 0 1 3 6 0 28/08/2024
  • 22.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 22 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, values[4] becomes 10 (4 + 6) After the fourth iteration 0 1 2 3 4 0 1 3 6 10 28/08/2024
  • 23.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 23 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 5 After the fourth iteration 0 1 2 3 4 0 1 3 6 10 28/08/2024
  • 24.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 24 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i ( =5) < 5 is false. Exit the loop After the fourth iteration 0 1 2 3 4 0 1 3 6 10 28/08/2024
  • 25.
    Liang, Introduction toJava Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 25 Trace Program with Arrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[0] is 11 (1 + 10) 0 1 2 3 4 11 1 3 6 10 28/08/2024
  • 26.
    28/08/2024 26 Initializing arrayswith input values java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter " + myList.length + " values: "); for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble();
  • 27.
    28/08/2024 27 Initializing arrayswith random values for (int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100; }
  • 28.
    28/08/2024 28 Printing arrays for(int i = 0; i < myList.length; i++) { System.out.print(myList[i] + " "); }
  • 29.
    28/08/2024 29 Summing allthe elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; }
  • 30.
    28/08/2024 30 Finding thelargest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; }
  • 31.
  • 32.
  • 33.
    28/08/2024 33 Enhanced forLoop (for-each loop) for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.
  • 34.
    28/08/2024 34 Self-check Write anenhanced for loop that prints all elements in the array values. Answer: for (double x:values) { System.out.println(x); }
  • 35.
    28/08/2024 35 Read onehundred numbers, compute their average, and find out how many numbers are above the average. int n1, n2,…, n100; Scanner input = new Scanner(System.in); n1 = input.nextInput(); n2 = input.nextInput(); n3 = input.nextInput(); ..... n100 = input.nextInput();
  • 36.
    28/08/2024 36 Solution throughArrays int [] n = new int[100]; Scanner input = new Scanner(System.in); for (int i=0; i < 100; i++) { n[i] = input.nextInt(); }
  • 37.
    28/08/2024 37 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: list2 = list1;
  • 38.
    28/08/2024 38 Copying Arrays Usinga loop: int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];
  • 39.
    28/08/2024 39 Passing Arraysto Methods public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } Invoke the method int[] list = {3, 1, 2, 6, 4, 2}; printArray(list); Invoke the method printArray(new int[]{3, 1, 2, 6, 4, 2}); Anonymous array
  • 40.
    28/08/2024 40 Searching Arrays Searchingis the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search. public class LinearSearch { /** The method for finding a key in the list */ public static int linearSearch(int[] list, int key) { for (int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } } list key Compare key with list[i] for i = 0, 1, … [0] [1] [2] …
  • 41.
    41 Linear Search Animation 64 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 3 3 3 3 3 3 Key List 28/08/2024
  • 42.
    42 Binary Search 28/08/2024 For binarysearch to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order. e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79 The binary search first compares the key with the element in the middle of the array.
  • 43.
    43 Binary Search, cont. 28/08/2024 •If the key is less than the middle element, you only need to search the key in the first half of the array. • If the key is equal to the middle element, the search ends with a match. • If the key is greater than the middle element, you only need to search the key in the second half of the array. Consider the following three cases:
  • 44.
    28/08/2024 44 Binary Search 12 3 4 6 7 8 9 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 8 8 8 Key List
  • 45.
  • 46.
    28/08/2024 46 Binary Search [0][1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 2 4 7 10 11 45 50 59 60 66 69 70 79 key is 54 key > 50 list mid [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] key < 66 key < 59 high low mid high low list [7] [8] mid high low list 59 60 66 69 70 79 59 60 [6] [7] [8] high low 59 60
  • 47.
    28/08/2024 47 Binary Search ThebinarySearch method returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns -insertion point - 1. The insertion point is the point at which the key would be inserted into the list.
  • 48.
    28/08/2024 48 2D ArrayDeclaration and Creation  2D arrays are used to store a matrix or a table Declaring Array Variables elementType[][] arrayRefVar; e.g. int[][] matrix;  Declaration of an array variable does not allocate any space in memory for the array Creating Arrays arrayRefVar = new elementType[rowSize][columnsize]; e.g. int[][] matrix = new int[5][5];
  • 49.
    28/08/2024 49 2D ArrayDeclaration and Creation Assigning Value to elements arrayRefVar[index2][index2] = value; e.g. matrix[2][1] = 7;
  • 50.
    28/08/2024 50 Array Size A two-dimensional array is actually an array in which each element is a one-dimensional array  If x = new int[3][4] then x[0], x[1], and x[2] are one-dimensional arrays and each contains four elements
  • 51.
    28/08/2024 51 Initializing andProcessing 2D Arrays
  • 52.
    28/08/2024 52 Some Examplesof Processing 2D Arrays  Initializing arrays with input values java.util.Scanner input = new Scanner(System.in); System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: "); for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = input.nextInt(); } }  Initializing arrays with random values for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = (int)(Math.random() * 100); } }  Displaying arrays for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " "); }
  • 53.
    28/08/2024 53 Multi DimensionalArrays  n-dimensional Array means collection of (n-1)-dimensional Arrays  The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables  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];
  • 54.
    28/08/2024 54 ArrayList  Usefulclass for storing objects  Arrays can be used to store objects but once the array is created, its size is fixed.  Java provides the ArrayList class that can be used to store an unlimited number of objects  ArrayList supports dynamic arrays  Defined in java.util package
  • 55.
    28/08/2024 55 ArrayList  Constructorsof ArrayList class are ArrayList() : creates an empty array list with an initial capacity sufficient to hold 10 elements. e.g. ArrayList list =new ArrayList(); ArrayList(int capacity) : creates an array list that has the specified initial capacity. e.g. ArrayList list =new ArrayList(20); ArrayList(Collection c) : creates an array list that is initialized with the elements of the collection c. e.g. ArrayList l = new ArrayList(list); Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged
  • 56.
    28/08/2024 56 Methods ofArrayList 1. void add(int index, Object element)  Inserts the specified element at the specified position index in this list.  Throws IndexOutOfBoundsException if the specified index is is out of range. 2. boolean add(Object o)  Appends the specified element to the end of this list. 3. boolean addAll(Collection c )  Appends all of the elements in the specified collection to the end of this list.  Throws NullPointerException if the specified collection is null. 4. boolean addAll(int index, Collection c )  Inserts all of the elements of the specified collection into this list, starting at the specified position.  Throws NullPointerException if the specified collection is null.
  • 57.
    28/08/2024 57 Methods ofArrayList 5. void clear() : Removes all of the elements from this list. 6. Object remove(int index) : Removes the element at the specified position in this list. 7. Object clone() : Returns a shallow copy of this ArrayList. 8. int size(): Returns the number of elements in the list. 9. boolean contains(Object o): Returns true if this list contains the specified element.
  • 58.
    28/08/2024 58 Methods ofArrayList 10. Object get(int index): Returns the element at the specified position in this list. 11. Object set(int index, o Object): Sets the element at the specified index. 12. int indexOf(Object o): Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain the element. 13. int lastIndexOf(Object o):Returns the index in this list of the last occurrence of the specified element, or -1. 14. void ensureCapacity(int minCapacity) : Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
  • 59.
  • 60.