Lecture 8 Arrays in Java
Lecture 8 Arrays in Java
IN2203
Fundamentals of Programming
(Java)
Instructor
Dr. Muhammad Waqar
muhammad.aslam@purescollege.ca
Arrays
• An array is a group of like-typed variables that are referred to by a common
name.
Tests
• Arrays of any type can be created and may have one or more dimensions.
• A specific element in an array is accessed by its index.
• Arrays offer a convenient means of grouping related information.
• A one-dimensional array is, essentially, a list of like-typed variables.
• To create an array, you first must create an array variable of the desired type.
The general form of a one-dimensional array declaration is
• type var-name[ ];
• int month_days[];
1
7/29/2020
Arrays
• Although this declaration (int month_days[]) establishes the fact that
month_days is an array variable, no array actually exists.
• The value of month_days is set to null,Tests
which represents an array with no
value.
• To link month_days with an actual, physical array of integers, you must
allocate one using new and assign it to month_days.
• new is a special operator that allocates memory.
• Once an array is created, its size is fixed. An array reference variable is used to
access the elements in an array using an index.
2
7/29/2020
System.out.println(month_days[1]);
3
7/29/2020
Note: We use for loop for arrays because length of array is already known.
• Ask user to enter the actual numbers for which average has to be taken and
save it in an array using for loop
• Use another for loop to scan through array and calculate the sum and average
4
7/29/2020
Code
System.out.print("Please specify total number of entrie:\t");
Scanner input = new Scanner(System.in);
int entries = input.nextInt(); Tests
double[] myList = new double[entries];
System.out.print("Enter " + myList.length + " values and press
enter after every value: ");
for (int i = 0; i < myList.length; i++){
myList[i] = input.nextDouble();}
int sum = 0;
for (int i = 0; i < myList.length; i++){
sum+= myList[i];}
double average = sum/myList.length;
System.out.print("Average is: \t" + average);
10
Array Initialization
• Arrays can be initialized when they are declared.
• An array initializer is a list of comma-separated expressions surrounded by
Tests
curly braces. The commas separate the values of the array elements.
• The array will automatically be created large enough to hold the number of
elements you specify in the array initializer. There is no need to use new.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
10
5
7/29/2020
11
Practice Program
2- Use Scanner class to ask user which month days he/she wants to know.
11
12
12
6
7/29/2020
13
Practice Problem
Declare an array and initialize it with few values.
Tests
Use a for loop to scan through this array and find out the maximum value in this array.
13
14
Tests
int max = myList[0];
for (int i = 1; i < myList.length; i++){
if (myList[i]>max)
max=myList[i];
}
14
7
7/29/2020
15
Practice problem
Writing a program for shifting the elements one position to the left and filling the last
element with the first element:
Tests
15
16
foreach loop
• Java supports a convenient for loop, known as a foreach loop, which enables
you to traverse the array sequentially without using an index variable.
Tests
• For example, the following code displays all the elements in the array myList:
• You can read the code as “for each element e in myList, do the following.”
Note that the variable, e, must be declared as the same type as the elements
in myList.
16
8
7/29/2020
17
Practice problem
Declare and initialize an array and use foreach loop to print all elements of array
in one line with a tab between the elements.
Tests
17
18
Copying Arrays
• To copy the contents of one array into another, you have to copy the array’s individual
elements into the other array.
• Often, in a program, you need to duplicate an array or a part of an array. In such cases
Tests
you could attempt to use the assignment statement (=), as follows:
list2 = list1;
• However, this statement does not copy the contents of the array referenced by list1
to list2, but instead merely copies the reference value from list1 to list2. After this
statement, list1 and list2 reference the same array
18
9
7/29/2020
19
Copying Arrays
• In Java, you can use assignment statements to copy primitive data type variables, but
not arrays.
• Assigning one array variable to another array variable actually copies one reference to
Tests
another and makes both variables point to the same memory location.
• There are three ways to copy arrays:
19
20
20
10
7/29/2020
21
• The parameters srcPos and tarPos indicate the starting positions in sourceArray and
targetArray, respectively.
• The number of elements copied from sourceArray to targetArray is indicated by
length. For example, you can rewrite the loop using the following statement:
• System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
• The arraycopy method does not allocate memory space for the target array. The
target array must have already been created with its memory space allocated. After
the copying takes place, targetArray and sourceArray have the same content but
independent memory locations.
21
22
22
11
7/29/2020
23
23
24
24
12
7/29/2020
25
25
26
26
13
7/29/2020
27
Searching Arrays
• Searching is the process of looking for a specific element in an array
• Two commonly used approaches are, linear search and binary search.
27
28
28
14
7/29/2020
29
Write a program which uses linear search method to find index of 6 in this array.
Tests
int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
29
30
• If the key is less than the middle element, you need to continue to search for the
key only 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 need to continue to search for
the key only in the second half of the array.
30
15
7/29/2020
31
31
32
Write a program which uses binary search method to find index of 11 in this array.
Tests
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
32
16
7/29/2020
33
33
34
Tests
34
17
7/29/2020
35
35
36
• double m[][] = {
• { 0*0, 1*0, 2*0, 3*0 },
• { 0*1, 1*1, 2*1, 3*1 },
• { 0*2, 1*2, 2*2, 3*2 },
• { 0*3, 1*3, 2*3, 3*3 }
• };
• Write a program to create this multi dimensional array and print its element at
3rd row and 2nd column.
36
18