SlideShare a Scribd company logo
Object – Oriented Programming
Week 5 –Arrays
Ferdin Joe John Joseph, PhD
Faculty of Information Technology
Thai-Nichi Institute of Technology
Arrays
Faculty of Information Technology,
Thai-Nichi Institute of Technology
2
3
Introducing Arrays
Array is a data structure that represents a collection
of the same types of data.
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
double[] myList = new double[10];
myList reference
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
Array reference
variable
Array element at
index 5
4
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
• datatype arrayRefVar[]; // This style is
allowed, but not preferred
Example:
double myList[];
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
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];
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
8
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.
9
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 in
Figure 6.1, 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];
10
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];
11
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.
12
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;
13
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};
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] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
Declare array variable values, create
an array, and assign its reference to
values
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
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] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i becomes 1
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
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] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=1) is less than 5
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
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 line is executed, value[1] is 1
After the first iteration
0
1
2
3
4
0
1
0
0
0
animation
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] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After i++, i becomes 2
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
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] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (= 2) is less than 5
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
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 line is executed,
values[2] is 3 (2 + 1)
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
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];
}
}
After this, i becomes 3.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
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];
}
}
i (=3) is still less than 5.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
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 this line, values[3] becomes 6 (3 + 3)
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
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];
}
}
After this, i becomes 4
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
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];
}
}
i (=4) is still less than 5
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
26
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
animation
27
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
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
28
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
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
29
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
animation
30
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)
31
Enhanced for Loop
JDK 1.5 introduced a new 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.
JDK 1.5
Feature
32
Example: Assigning Grades
• Objective: read student scores (int), get the
best score, and then assign grades based on
the following scheme:
– 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.
33
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;
Contents
of list1
list1
Contents
of list2
list2
Before the assignment
list2 = list1;
Contents
of list1
list1
Contents
of list2
list2
After the assignment
list2 = list1;
Garbage
34
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];
35
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
36
Linear Search
The linear search approach compares the
key element, key, sequentially with each
element in the array list. The method
continues to do so until the key matches
an element in the list or the list is
exhausted without a match being found. If
a match is made, the linear search returns
the index of the element in the array that
matches the key. If no match is found, the
search returns -1.
37
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
animation
Key List
38
From Idea to Solution
/** 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;
}
int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // returns 1
int j = linearSearch(list, -4); // returns -1
int k = linearSearch(list, -3); // returns 5
Trace the method
Two-Dimensional Arrays
• A one-dimensional array stores a list of
elements
• A two-dimensional array can be thought
of as a table of elements, with rows and
columns
one
dimension
two
dimensions
Two-Dimensional Arrays
• To be precise, in Java a two-dimensional array is an
array of arrays
• A two-dimensional array is declared by specifying the
size of each dimension separately:
int[][] scores = new int[12][50];
• A array element is referenced using two index values:
value = scores[3][6]
• The array stored in one row can be specified using
one index
Arrays of Arrays
• Two-Dimensional arrays
– float[][] temperature=new float[10][365];
– 10 arrays each having 365 elements
– First index: specifies array (row)
– Second Index: specifies element in that array
(column)
– In JAVA float is 4 bytes, total
Size=4*10*365=14,600 bytes
Graphical Representation
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
Sample[0]
Sample[1]
Sample[2]
Initializing Array of Arrays
int[][] array2D = { {99, 42, 74, 83, 100}, {90,
91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61,
89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50,
65, 92, 87, 94}, {43, 98, 78, 56, 99} };
//5 rows with 5 elements each
Arrays of Arrays of Varying
Length
• All arrays do not have to be of the same
length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];
• Not required to define all arrays
Initializing Varying Size Arrays
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
Array of Arrays Length
long[][] primes = new long[20][];
primes[2] = new long[30];
System.out.println(primes.length); //Number of arrays
System.out.println(primes[2].length);//Number of elements in the second array
OUTPUT:
20
30
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
// print out the array
for ( int row=0; row < uneven.length; row++ ) //changes row
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length; col++ ) //changes column
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
Output
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
Faculty of Information Technology,
Thai-Nichi Institute of Technology
49
An Ordered Collection: ArrayList
• ArrayList is a Java class that specializes in
representing an ordered collection of things
• The ArrayList class is defined in the Java
libraries
– part of the java.util package
• We can store any kind of object in an ArrayList
– myList.add(theDog);
• We can retrieve an object from the ArrayList by
specifying its index number
– myList.get(0)
Faculty of Information Technology,
Thai-Nichi Institute of Technology
50
ArrayList
• ArrayList()
– This constructor builds an empty list with an initial
capacity of 10
• int size()
– This method returns the number of elements in this
list
• boolean add(Object o)
– This method appends the specified element to the
end of this list and increases the size of the array if
needed
• Object get(int index)
– This method returns the element at the specified
position
Faculty of Information Technology,
Thai-Nichi Institute of Technology
51
Using ArrayLists
• ArrayList is part of the java.util package
– import java.util.*; to use ArrayList
• Creating a list
• ArrayList names = new ArrayList ( );
• Getting the size
• int numberOfNames = names.size( );
• Adding things
• names.add("Billy");
• names.add("Susan");
• names.add("Frodo");
NameList.java
Faculty of Information Technology,
Thai-Nichi Institute of Technology
52
Using ArrayLists : import
• ArrayList is part of the java.util package
– import java.util.ArrayList; to use ArrayList
• The import statement tells the Java
compiler where to look when it can’t find a
class definition in the local directory
– We tell the compiler to look in package
java.util for the definition of ArrayList by
putting an import statement at the top of the
source code file
– Java always looks in package java.lang on its
own
Faculty of Information Technology,
Thai-Nichi Institute of Technology
53
Using ArrayLists : constructor
• Creating a new ArrayList object
• ArrayList names = new ArrayList ( );
• There are several constructors available
– ArrayList()
• Construct an empty list with an initial capacity of 10
– ArrayList(int initialCapacity)
• Construct an empty list with the specified initial capacity
– ArrayList(Collection c)
• Construct a list containing elements from another collection
Faculty of Information Technology,
Thai-Nichi Institute of Technology
54
Using ArrayLists : size
• Getting the size
• int numberOfNames = names.size( );
• size() method returns integer value that
caller can use to control looping, check for
limits, etc
– Design pattern: The object keeps track of
relevant information, and can tell the caller when
there is a need to know
Faculty of Information Technology,
Thai-Nichi Institute of Technology
55
Using ArrayLists : add
• Adding things
• names.add("Billy");
• add(Object o) method adds an object to the
list at the end of the list
• The object can be of any class type
– String, File, InputStream, …
– can’t add “primitive” types like int or double
directly
• Can use the wrapper classes like Integer to store
primitives
Faculty of Information Technology,
Thai-Nichi Institute of Technology
56
Using ArrayLists: get
• ArrayLists provide indexed access
– We can ask for the ith item of the list, where
the first item is at index 0, the second at index
1, and the last item is at index n-1 (where n is
the size of the collection).
ArrayList names = new ArrayList ( );
names.add("Billy");
names.add("Susan");
Object x = names.get(0);
Object y = names.get(1);

More Related Content

What's hot (20)

PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
16. Arrays Lists Stacks Queues
Intro C# Book
 
PPT
Ch02 primitive-data-definite-loops
James Brotsos
 
PPTX
06.Loops
Intro C# Book
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PPTX
13. Java text processing
Intro C# Book
 
PPT
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
PPT
Chapter 2 Method in Java OOP
Khirulnizam Abd Rahman
 
PPTX
10. Recursion
Intro C# Book
 
PPTX
Java Foundations: Arrays
Svetlin Nakov
 
PPTX
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
PPT
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
PPT
Chapter 2 Java Methods
Khirulnizam Abd Rahman
 
PPTX
Java introduction
Samsung Electronics Egypt
 
PPTX
Python basics
TIB Academy
 
PPTX
Java Tutorial: Part 1. Getting Started
Svetlin Nakov
 
PPTX
09. Java Methods
Intro C# Book
 
PPT
Parameters
James Brotsos
 
PPTX
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 
16. Arrays Lists Stacks Queues
Intro C# Book
 
Ch02 primitive-data-definite-loops
James Brotsos
 
06.Loops
Intro C# Book
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
13. Java text processing
Intro C# Book
 
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
Chapter 2 Method in Java OOP
Khirulnizam Abd Rahman
 
10. Recursion
Intro C# Book
 
Java Foundations: Arrays
Svetlin Nakov
 
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
Chapter 2 Java Methods
Khirulnizam Abd Rahman
 
Java introduction
Samsung Electronics Egypt
 
Python basics
TIB Academy
 
Java Tutorial: Part 1. Getting Started
Svetlin Nakov
 
09. Java Methods
Intro C# Book
 
Parameters
James Brotsos
 
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 

Similar to DSA 103 Object Oriented Programming :: Week 5 (20)

PPTX
07+08slide.pptx
MURADSANJOUM
 
PPT
07slide.ppt
ankurgupta857016
 
PPT
06slide
Dorothea Chaffin
 
PPTX
Arrays and Detailed explanation of Array
Dr. Jasmine Beulah Gnanadurai
 
PPT
05slide_arrays_creation_searching_sorting.ppt
ramesh504657
 
PPT
Capitulo 1 de java array unidimensionales
DiegoGamboaSafla
 
PPTX
Data Structures and Algorithoms 07slide - 1D Arrays.pptx
AliciaLee77
 
PPT
Java™ (OOP) - Chapter 6: "Arrays"
Gouda Mando
 
PPT
Fp201 unit4
rohassanie
 
PPTX
Arrays in Java
Abhilash Nair
 
PPTX
6_Array.pptx
shafat6712
 
PPTX
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
PPT
Ch5 array nota
Hattori Sidek
 
PDF
Java - Arrays Concepts
Victer Paul
 
PPT
cse dse eee btech bsc and more to go on and on.ppt
AbuObaidhaArin
 
PPTX
Arrays in CPP
Shakila Mahjabin
 
PPT
Arrays in c programing. practicals and .ppt
Carlos701746
 
PPTX
arrays-120712074248-phpapp01
Abdul Samee
 
PPTX
Chapter 7.1
sotlsoc
 
PPTX
COM1407: Arrays
Hemantha Kulathilake
 
07+08slide.pptx
MURADSANJOUM
 
07slide.ppt
ankurgupta857016
 
Arrays and Detailed explanation of Array
Dr. Jasmine Beulah Gnanadurai
 
05slide_arrays_creation_searching_sorting.ppt
ramesh504657
 
Capitulo 1 de java array unidimensionales
DiegoGamboaSafla
 
Data Structures and Algorithoms 07slide - 1D Arrays.pptx
AliciaLee77
 
Java™ (OOP) - Chapter 6: "Arrays"
Gouda Mando
 
Fp201 unit4
rohassanie
 
Arrays in Java
Abhilash Nair
 
6_Array.pptx
shafat6712
 
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
Ch5 array nota
Hattori Sidek
 
Java - Arrays Concepts
Victer Paul
 
cse dse eee btech bsc and more to go on and on.ppt
AbuObaidhaArin
 
Arrays in CPP
Shakila Mahjabin
 
Arrays in c programing. practicals and .ppt
Carlos701746
 
arrays-120712074248-phpapp01
Abdul Samee
 
Chapter 7.1
sotlsoc
 
COM1407: Arrays
Hemantha Kulathilake
 
Ad

More from Ferdin Joe John Joseph PhD (20)

PDF
Invited Talk DGTiCon 2022
Ferdin Joe John Joseph PhD
 
PDF
Week 12: Cloud AI- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Week 11: Cloud Native- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Week 10: Cloud Security- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Week 9: Relational Database Service Alibaba Cloud- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Week 7: Object Storage Service Alibaba Cloud- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Week 6: Server Load Balancer and Auto Scaling Alibaba Cloud- DSA 441 Cloud Co...
Ferdin Joe John Joseph PhD
 
PDF
Week 5: Elastic Compute Service (ECS) with Alibaba Cloud- DSA 441 Cloud Compu...
Ferdin Joe John Joseph PhD
 
PDF
Week 4: Big Data and Hadoop in Alibaba Cloud - DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Week 3: Virtual Private Cloud, On Premise, IaaS, PaaS, SaaS - DSA 441 Cloud C...
Ferdin Joe John Joseph PhD
 
PDF
Week 2: Virtualization and VM Ware - DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Week 1: Introduction to Cloud Computing - DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
PDF
Sept 6 2021 BTech Artificial Intelligence and Data Science curriculum
Ferdin Joe John Joseph PhD
 
PDF
Hadoop in Alibaba Cloud
Ferdin Joe John Joseph PhD
 
PDF
Cloud Computing Essentials in Alibaba Cloud
Ferdin Joe John Joseph PhD
 
PDF
Transforming deep into transformers – a computer vision approach
Ferdin Joe John Joseph PhD
 
PDF
Week 11: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
PDF
Week 10: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
PDF
Week 9: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
PDF
Week 8: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
Invited Talk DGTiCon 2022
Ferdin Joe John Joseph PhD
 
Week 12: Cloud AI- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Week 11: Cloud Native- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Week 10: Cloud Security- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Week 9: Relational Database Service Alibaba Cloud- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Week 7: Object Storage Service Alibaba Cloud- DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Week 6: Server Load Balancer and Auto Scaling Alibaba Cloud- DSA 441 Cloud Co...
Ferdin Joe John Joseph PhD
 
Week 5: Elastic Compute Service (ECS) with Alibaba Cloud- DSA 441 Cloud Compu...
Ferdin Joe John Joseph PhD
 
Week 4: Big Data and Hadoop in Alibaba Cloud - DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Week 3: Virtual Private Cloud, On Premise, IaaS, PaaS, SaaS - DSA 441 Cloud C...
Ferdin Joe John Joseph PhD
 
Week 2: Virtualization and VM Ware - DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Week 1: Introduction to Cloud Computing - DSA 441 Cloud Computing
Ferdin Joe John Joseph PhD
 
Sept 6 2021 BTech Artificial Intelligence and Data Science curriculum
Ferdin Joe John Joseph PhD
 
Hadoop in Alibaba Cloud
Ferdin Joe John Joseph PhD
 
Cloud Computing Essentials in Alibaba Cloud
Ferdin Joe John Joseph PhD
 
Transforming deep into transformers – a computer vision approach
Ferdin Joe John Joseph PhD
 
Week 11: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
Week 10: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
Week 9: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
Week 8: Programming for Data Analysis
Ferdin Joe John Joseph PhD
 
Ad

Recently uploaded (20)

PDF
apidays Singapore 2025 - How APIs can make - or break - trust in your AI by S...
apidays
 
PDF
Using AI/ML for Space Biology Research
VICTOR MAESTRE RAMIREZ
 
PPTX
Listify-Intelligent-Voice-to-Catalog-Agent.pptx
nareshkottees
 
PDF
Technical-Report-GPS_GIS_RS-for-MSF-finalv2.pdf
KPycho
 
PPTX
SHREYAS25 INTERN-I,II,III PPT (1).pptx pre
swapnilherage
 
PPTX
03_Ariane BERCKMOES_Ethias.pptx_AIBarometer_release_event
FinTech Belgium
 
PDF
Development and validation of the Japanese version of the Organizational Matt...
Yoga Tokuyoshi
 
PDF
Driving Employee Engagement in a Hybrid World.pdf
Mia scott
 
PPTX
Powerful Uses of Data Analytics You Should Know
subhashenia
 
PPTX
01_Nico Vincent_Sailpeak.pptx_AI_Barometer_2025
FinTech Belgium
 
PPTX
美国史蒂文斯理工学院毕业证书{SIT学费发票SIT录取通知书}哪里购买
Taqyea
 
PDF
apidays Singapore 2025 - The API Playbook for AI by Shin Wee Chuang (PAND AI)
apidays
 
PPTX
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
PPTX
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
PPTX
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
PPTX
在线购买英国本科毕业证苏格兰皇家音乐学院水印成绩单RSAMD学费发票
Taqyea
 
PDF
1750162332_Snapshot-of-Indias-oil-Gas-data-May-2025.pdf
sandeep718278
 
PDF
SQL for Accountants and Finance Managers
ysmaelreyes
 
PDF
apidays Singapore 2025 - From API Intelligence to API Governance by Harsha Ch...
apidays
 
PDF
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 
apidays Singapore 2025 - How APIs can make - or break - trust in your AI by S...
apidays
 
Using AI/ML for Space Biology Research
VICTOR MAESTRE RAMIREZ
 
Listify-Intelligent-Voice-to-Catalog-Agent.pptx
nareshkottees
 
Technical-Report-GPS_GIS_RS-for-MSF-finalv2.pdf
KPycho
 
SHREYAS25 INTERN-I,II,III PPT (1).pptx pre
swapnilherage
 
03_Ariane BERCKMOES_Ethias.pptx_AIBarometer_release_event
FinTech Belgium
 
Development and validation of the Japanese version of the Organizational Matt...
Yoga Tokuyoshi
 
Driving Employee Engagement in a Hybrid World.pdf
Mia scott
 
Powerful Uses of Data Analytics You Should Know
subhashenia
 
01_Nico Vincent_Sailpeak.pptx_AI_Barometer_2025
FinTech Belgium
 
美国史蒂文斯理工学院毕业证书{SIT学费发票SIT录取通知书}哪里购买
Taqyea
 
apidays Singapore 2025 - The API Playbook for AI by Shin Wee Chuang (PAND AI)
apidays
 
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
在线购买英国本科毕业证苏格兰皇家音乐学院水印成绩单RSAMD学费发票
Taqyea
 
1750162332_Snapshot-of-Indias-oil-Gas-data-May-2025.pdf
sandeep718278
 
SQL for Accountants and Finance Managers
ysmaelreyes
 
apidays Singapore 2025 - From API Intelligence to API Governance by Harsha Ch...
apidays
 
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 

DSA 103 Object Oriented Programming :: Week 5

  • 1. Object – Oriented Programming Week 5 –Arrays Ferdin Joe John Joseph, PhD Faculty of Information Technology Thai-Nichi Institute of Technology
  • 2. Arrays Faculty of Information Technology, Thai-Nichi Institute of Technology 2
  • 3. 3 Introducing Arrays Array is a data structure that represents a collection of the same types of data. 5.6 4.5 3.3 13.2 4 34.33 34 45.45 99.993 11123 double[] myList = new double[10]; myList reference myList[0] myList[1] myList[2] myList[3] myList[4] myList[5] myList[6] myList[7] myList[8] myList[9] Element value Array reference variable Array element at index 5
  • 4. 4 Declaring Array Variables • datatype[] arrayRefVar; Example: double[] myList; • datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];
  • 5. 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. 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];
  • 7. 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
  • 8. 8 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.
  • 9. 9 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 in Figure 6.1, 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];
  • 10. 10 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];
  • 11. 11 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.
  • 12. 12 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;
  • 13. 13 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};
  • 14. 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] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } Declare array variable values, create an array, and assign its reference to values After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 15. 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] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } i becomes 1 After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 16. 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] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } i (=1) is less than 5 After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 17. 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 line is executed, value[1] is 1 After the first iteration 0 1 2 3 4 0 1 0 0 0 animation
  • 18. 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] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 2 animation After the first iteration 0 1 2 3 4 0 1 0 0 0
  • 19. 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] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } i (= 2) is less than 5 animation After the first iteration 0 1 2 3 4 0 1 0 0 0
  • 20. 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 line is executed, values[2] is 3 (2 + 1) After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 21. 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]; } } After this, i becomes 3. After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 22. 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]; } } i (=3) is still less than 5. After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 23. 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 this line, values[3] becomes 6 (3 + 3) After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 24. 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]; } } After this, i becomes 4 After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 25. 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]; } } i (=4) is still less than 5 After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 26. 26 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 animation
  • 27. 27 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 animation After the fourth iteration 0 1 2 3 4 0 1 3 6 10
  • 28. 28 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 animation After the fourth iteration 0 1 2 3 4 0 1 3 6 10
  • 29. 29 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 animation
  • 30. 30 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)
  • 31. 31 Enhanced for Loop JDK 1.5 introduced a new 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. JDK 1.5 Feature
  • 32. 32 Example: Assigning Grades • Objective: read student scores (int), get the best score, and then assign grades based on the following scheme: – 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.
  • 33. 33 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; Contents of list1 list1 Contents of list2 list2 Before the assignment list2 = list1; Contents of list1 list1 Contents of list2 list2 After the assignment list2 = list1; Garbage
  • 34. 34 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];
  • 35. 35 The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
  • 36. 36 Linear Search The linear search approach compares the key element, key, sequentially with each element in the array list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1.
  • 37. 37 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 animation Key List
  • 38. 38 From Idea to Solution /** 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; } int[] list = {1, 4, 4, 2, 5, -3, 6, 2}; int i = linearSearch(list, 4); // returns 1 int j = linearSearch(list, -4); // returns -1 int k = linearSearch(list, -3); // returns 5 Trace the method
  • 39. Two-Dimensional Arrays • A one-dimensional array stores a list of elements • A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions
  • 40. Two-Dimensional Arrays • To be precise, in Java a two-dimensional array is an array of arrays • A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; • A array element is referenced using two index values: value = scores[3][6] • The array stored in one row can be specified using one index
  • 41. Arrays of Arrays • Two-Dimensional arrays – float[][] temperature=new float[10][365]; – 10 arrays each having 365 elements – First index: specifies array (row) – Second Index: specifies element in that array (column) – In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
  • 42. Graphical Representation 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 Sample[0] Sample[1] Sample[2]
  • 43. Initializing Array of Arrays int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} }; //5 rows with 5 elements each
  • 44. Arrays of Arrays of Varying Length • All arrays do not have to be of the same length float[][] samples; samples=new float[6][];//defines # of arrays samples[2]=new float[6]; samples[5]=new float[101]; • Not required to define all arrays
  • 45. Initializing Varying Size Arrays int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; //Three arrays //First array has 3 elements //Second array has 2 elements //Third array has 5 elements
  • 46. Array of Arrays Length long[][] primes = new long[20][]; primes[2] = new long[30]; System.out.println(primes.length); //Number of arrays System.out.println(primes[2].length);//Number of elements in the second array OUTPUT: 20 30
  • 47. Sample Program class unevenExample3 { public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // print out the array for ( int row=0; row < uneven.length; row++ ) //changes row { System.out.print("Row " + row + ": "); for ( int col=0; col < uneven[row].length; col++ ) //changes column System.out.print( uneven[row][col] + " "); System.out.println(); } } }
  • 48. Output Row 0: 1 9 4 Row 1: 0 2 Row 2: 0 1 2 3 4
  • 49. Faculty of Information Technology, Thai-Nichi Institute of Technology 49 An Ordered Collection: ArrayList • ArrayList is a Java class that specializes in representing an ordered collection of things • The ArrayList class is defined in the Java libraries – part of the java.util package • We can store any kind of object in an ArrayList – myList.add(theDog); • We can retrieve an object from the ArrayList by specifying its index number – myList.get(0)
  • 50. Faculty of Information Technology, Thai-Nichi Institute of Technology 50 ArrayList • ArrayList() – This constructor builds an empty list with an initial capacity of 10 • int size() – This method returns the number of elements in this list • boolean add(Object o) – This method appends the specified element to the end of this list and increases the size of the array if needed • Object get(int index) – This method returns the element at the specified position
  • 51. Faculty of Information Technology, Thai-Nichi Institute of Technology 51 Using ArrayLists • ArrayList is part of the java.util package – import java.util.*; to use ArrayList • Creating a list • ArrayList names = new ArrayList ( ); • Getting the size • int numberOfNames = names.size( ); • Adding things • names.add("Billy"); • names.add("Susan"); • names.add("Frodo"); NameList.java
  • 52. Faculty of Information Technology, Thai-Nichi Institute of Technology 52 Using ArrayLists : import • ArrayList is part of the java.util package – import java.util.ArrayList; to use ArrayList • The import statement tells the Java compiler where to look when it can’t find a class definition in the local directory – We tell the compiler to look in package java.util for the definition of ArrayList by putting an import statement at the top of the source code file – Java always looks in package java.lang on its own
  • 53. Faculty of Information Technology, Thai-Nichi Institute of Technology 53 Using ArrayLists : constructor • Creating a new ArrayList object • ArrayList names = new ArrayList ( ); • There are several constructors available – ArrayList() • Construct an empty list with an initial capacity of 10 – ArrayList(int initialCapacity) • Construct an empty list with the specified initial capacity – ArrayList(Collection c) • Construct a list containing elements from another collection
  • 54. Faculty of Information Technology, Thai-Nichi Institute of Technology 54 Using ArrayLists : size • Getting the size • int numberOfNames = names.size( ); • size() method returns integer value that caller can use to control looping, check for limits, etc – Design pattern: The object keeps track of relevant information, and can tell the caller when there is a need to know
  • 55. Faculty of Information Technology, Thai-Nichi Institute of Technology 55 Using ArrayLists : add • Adding things • names.add("Billy"); • add(Object o) method adds an object to the list at the end of the list • The object can be of any class type – String, File, InputStream, … – can’t add “primitive” types like int or double directly • Can use the wrapper classes like Integer to store primitives
  • 56. Faculty of Information Technology, Thai-Nichi Institute of Technology 56 Using ArrayLists: get • ArrayLists provide indexed access – We can ask for the ith item of the list, where the first item is at index 0, the second at index 1, and the last item is at index n-1 (where n is the size of the collection). ArrayList names = new ArrayList ( ); names.add("Billy"); names.add("Susan"); Object x = names.get(0); Object y = names.get(1);