0% found this document useful (0 votes)
32 views60 pages

Week 2 Lecture 02

Uploaded by

Tiến Anh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views60 pages

Week 2 Lecture 02

Uploaded by

Tiến Anh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

INFO1113 / COMP9003

Object-Oriented Programming

Lecture 2

The University of Sydney Page 1


Contents developed by Tyson Thomas
Always try to be in the green zone!

The University of Sydney Page 2


Acknowledgement of Country

I would like to acknowledge the Traditional Owners of Australia and recognise


their continuing connection to land, water and culture. I am currently on the land
of the Gadigal people of the Eora nation and pay my respects to their Elders,
past, present and emerging.

I further acknowledge the Traditional Owners of the country on which you are on
and pay respects to their Elders, past, present and future.

The University of Sydney Page 3


Copyright Warning

COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to you by or on behalf of the
University of Sydney pursuant to Part VB of the Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright under the Act. Any
further copying or communication of this material by you may be the subject of
copyright protection under the Act.
Do not remove this notice.

The University of Sydney Page 4


Topics: Part A

● Control Flow
● While/do-while/for loop
● For-each loop
● Static Methods

The University of Sydney Page 5


Loops
Remember flow control diagrams?

Refer to Chapter 4.1, page 237, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 6


Loops
Remember flow control diagrams?

5
What if we changed i to 5?

What would be the output


of this program?

Refer to Chapter 4.1, page 237, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 7


Loops

4 types of loops we can write within Java.

● while
● do-while
● for
● for-each

The constructs are part of the language’s syntax and typically follow a
similar pattern.

The University of Sydney Page 8


While loop

Syntax: while (condition) statement

As with if statements, for this branch to start and continue execution the
condition must be true.
A boolean expression is
evaluated here and is
checked on every
initialization; iteration.

while(condition) {

doWork() The body of the loop. It


will execute the following
increment/decrement; body until the condition
} is no longer met.

Refer to Chapter 4.1, pages 238-251, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 9


While loop

Syntax: while (condition) statement

As with if statements, for this branch to start and continue execution the
condition must be true.

int i = 30;
while(i < 40) {

doWork();
i += 1;
}

Refer to Chapter 4.1, pages 238-251, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 10


do-while loop

Syntax: do {} while(condition) statement

Similar to the while loop but it will always execute the block at-least
once and continue execution if condition is true.

The loop scope is


initialization; defined by the curly
do { braces. The do keyword
must be followed by the
while keyword after the
block definition.
doWork();
increment/decrement;
} while (condition) A boolean expression is
evaluated here and is
checked on every
iteration.

Refer to Chapter 4.1, pages 238-251, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 11


Let’s write some loops!

The University of Sydney Page 12


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

for( [initialization]; [condition]; [update] ) {

doWork();

Refer to Chapter 4.1, pages 251-260, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 13


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

for( [initialization]; [condition]; [update] ) {

doWork();
We are able to create
and initialise variables
} for our loop here. They
will be restricted to the
loop’s scope.

The University of Sydney Page 14


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

for( int i = 0; [condition]; [update] ) {

doWork();
A common variable is a
counter for our for loop.
}

The University of Sydney Page 15


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

for( int i = 0; [condition]; [update] ) {

doWork();
The boolean expression
to the inputted here.
} No different than a
while loop

The University of Sydney Page 16


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

for( int i = 0; i < 10; [update] ) {

doWork();
Let’s say we wanted to
loop 10 times
}

The University of Sydney Page 17


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

for( int i = 0; i < 10; [update] ) {

doWork();
This is the update
component. Were we
} update any variables
defined within the variable
section (or variables defined
in the outer scope)

The University of Sydney Page 18


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

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

doWork();
So we can increment by
1, similar to the while
} loop.

The University of Sydney Page 19


For loop

Syntax: for( [initialization]; [condition]; [update]) statement

for loops are broken up into 3 separate sections.

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

doWork();
So we can increment by
1, similar to the while
} loop.

Regardless you can always rewrite a for loop as a while loop.

The University of Sydney Page 20


Using a for-loop

The University of Sydney Page 21


okay, what about for-each?

The University of Sydney Page 22


For-each loop

Syntax: for( binding : collection ) statement

for-each loops involve the use of iterators (exception being arrays).

for( binding : collection ) {

doWork(binding);

Refer to Chapter 4.1, pages 260, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 23


For-each loop

Syntax: for( binding : collection ) statement

for-each loops involve the use of iterators (exception being arrays).

A collection is an object
that aggregates other
objects.

for( binding : collection ) {

doWork(binding);
A binding in this case is
just some variable that
} will represent an
element of the
collection.

The University of Sydney Page 24


For-each loop

Syntax: for( binding : collection ) statement

for-each loops involve the use of iterators (exception being arrays).

This is our collection type


here. Containing our
strings

for( String str : strings ) {

System.out.println(str);
Declaration of a String
variable that will be an
} element in the
collection.

The University of Sydney Page 25


For-each loop

Syntax: for( binding : collection ) statement

for-each loops involve the use of iterators (exception being arrays).

String[], ArrayList<String>,
List<String>,
Set<String>,
Deque<String>
for( String str : strings ) { …

System.out.println(str);

The University of Sydney Page 26


For-each loop

Syntax: for( binding : collection ) statement

for-each loops involve the use of iterators (exception being arrays).

for( String str : strings ) {

System.out.println(str);

What information are we missing by using a for-each loop?

The University of Sydney Page 27


For-each loop

Syntax: for( binding : collection ) statement

for-each loops involve the use of iterators (exception being arrays).

for( String str : strings ) {

System.out.println(str);

What information are we missing by using a for-each loop? an index

The University of Sydney Page 28


Using a for-each loop

The University of Sydney Page 29


Static Methods
Binds the method to the
Return type of the Method identifier, the
class. Without static it is Arguments of the method.
method. name we use to call it.
an instance method.

Syntax:
static [final] return_type name ([parameters])

A method is a stored set of instructions bound to an object. In the case of a


static method, the object is the class which it is defined in.

Example:

public static int addThree(int a, int b, int c) {


return a+b+c;
}

Refer to Chapter 6.2, pages 433-436, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 30


Demonstration: Static methods

The University of Sydney Page 31


Call Stack

Java is a stack-based language so when a method


is executed it is put onto a call-stack.
Latest being executed
The method being executed at the top of the
stack is the most recently called method.
a(....)
A method finishes executing once it has reached
a return state or for void method, once it has
z(....)
reached the end of method scope.
y(....)

f(....)

main(....)

Refer to JVM Specification, Java Virtual Machine Stacks, (https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5.2)

The University of Sydney Page 32


Let’s break down the call stack

The University of Sydney Page 33


Take a break!
When you come back, please complete the poll

The University of Sydney Page 34


Topics: Part B

● Arrays

● Multidimensional Arrays

● Strings

● StringBuilder

The University of Sydney Page 35


Arrays
An array is a contiguous block of memory containing multiple values of
the same type.

When an array is initialised the array will be allocated and will return the
address of where the array is stored.

Let’s say we have the following array:


Since an int is 4 bytes and we are accessing index 1, we will
move 4 bytes from starting address.
0x1000 + 4 = 0x1004. When reading the value here, we are
0x1004 dereferencing

0x100C

2 8 3 4 90 12 45 32 43 76 1 -9 2 44 65 78

0x1000 Let’s assume the array we have received is allocated at


0x1000 (address 4096), since an int is 4 bytes, what is the
0x1008 address of element at index 1

The University of Sydney Page 36


Array Initialisation

Within the java language we are able to intiailise an array in a few different
ways. Most commonly and what is typically used is allocate and specify size.

int[] numbers = new int[16];

However we can always initialise using static initialisation.

int[] numbers = {1, 2, 3, 4};

This translates to an array of length 4, containing the elements 1, 2, 3 and 4.

Similarly, we can initialise an array like so.


int[] numbers = new int[] {1, 2, 3, 4};

More commonly used when passing an array with values


known at compile time. This is because the compiler knows
the type being passed and what values it should contain.

Refer to Chapter 7.1, pages 525-541, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 37


Reference and primitive type arrays

We have seen primitive type arrays but what about reference type
arrays?

These types of arrays have a slightly different semantic meaning behind


them.

Using the String type as an example.

String[] numbers = new String[4];

Since it is a reference type it is initialising 4 references. A reference in


this instance is a memory address.

This infers that reference type arrays do not contain a string but a
reference to a string.

Refer to Chapter 7.1, pages 525-541, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 38


Reference and primitive type arrays

General rules with array initialisation


● Primitive integer types (byte, short, int, long) are initialised to 0 by default.
● Default value of elements of a boolean array are false.
● Floating point numbers such as float and double are initialised to 0.0f and
0.0d respectively.
● Elements of a char array is initialised to \u0000 (null character)
● Any Reference type is initialised to null.

Refer to Oracle Java Language Specification, (https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5)

The University of Sydney Page 39


Demonstration: Array Manipulation

The University of Sydney Page 40


Multi-dimensional arrays

We are not limited just creating single dimensional arrays. We are able
to create multi-dimensional arrays.

int[][] array = new int[3][3];

There are two types, one adheres to a matrix-like structure and the
other is commonly referred to as a jagged array.

int[][] jarray = new int[3][];

Arrays are also reference types. When initialised, the variable array will
contain 3 null elements. We are able to specify lengths on each
elements.
jarray[0] = new int[5];
jarray[1] = new int[10];

Refer to Oracle Java Language Specification, (https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5)


Refer to Chapter 7.1, pages 525-541, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 41


Multi-dimensional arrays

With the following code:

int[][] array = new int[2][];

It will initialise the 2 elements within the array to null. This allows us to
set each element to a separate array.

array[0] = new int[3];


array[1] = new int[5];

Memory 0x2000 0x4000

array 0x2000 0x4000


Values 0x2000 and 0x4000 are used for demonstration purposes and are not the actual addresses.

The University of Sydney Page 42


Traversals

So how do we traverse a multidimensional array? Like so:

int[][] array = new int[5][5]; We have some allocation of an array


that we will use
// set elements
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + “ ”);
}
System.out.println();
} Define the condition for the first
Some loop structure, in this case, a for
dimension.
loop

For the second dimension, since the


element at i is an array itself we are able to
access the length property.

The University of Sydney Page 43


Traversals

So how do we traverse a multidimensional array? Like so:

int[][] array = new int[5][5];


// set elements
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + “ ”);
}
System.out.println();
}

We can output the element at [i][j].

The University of Sydney Page 44


Traversals
So how do we traverse a multidimensional array? Like so:

int[][] array = new int[5][5];


// set elements
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + “ ”);
}
Let’s assume we set all the elements in
System.out.println(); array from 0-24.

> java ArrayOutput


01234
56789
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
<program end>

The University of Sydney Page 45


Demonstration: Multi-dimensional Array manipulation

The University of Sydney Page 46


String is Special!

The University of Sydney Page 47


Strings

String is a reference type that aggregates characters and Java treats


Strings as immutable.

When initialising a string type, the JVM will allocate memory to contain
the string.

String cat = "Meow";

When assigned, the string is allocated and binded to


the variable “cat”.

What happens with the following expression?


A string is immutable. For concatenation to occur, the
JVM will need to allocate a new String object to fit the
String cat = "Meow"; contents of the first string (“Meow”) and second string.

cat += ", says the cat!"

The University of Sydney Page 48


Strings

String is a reference type that aggregates characters and Java treats


Strings as immutable.

When initialising a string type, the JVM will allocate memory to contain
the string.

String cat = "Meow";

Meow
When assigned, the string is allocated and binded to
the variable “cat”.

What happens with the following expression?

Meow, says the cat


String cat = "Meow";
cat += ", says the cat!" Memory

The University of Sydney Page 49


Comparing strings

Any reference type variable holds onto the memory reference of the
object.

So let’s analyse the following


Meow

String cat1 = "Meow";


String cat2 = "Meow";

System.out.println(cat1 == cat2);

We can see when run the above the output will be true.
Memory

Hang on though… Let’s try something!


Refer to Chapter 3.2, pages 189-191 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 50


Comparing strings

Any reference type variable holds onto the memory reference of the
object.

So let’s analyse the following


Meow
String cat1 = "Meow";
String cat2 = new String("Meow");

System.out.println(cat1 == cat2); Meow

We can see when run the above the output will be false.
Memory

Refer to Chapter 3.2, pages 189=191 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 51


Comparing strings

Any reference type variable holds onto the memory reference of the
object.

So let’s analyse the following


Meow
String cat1 = "Meow"; -> 0x1000
String cat2 = new String("Meow"); -> 0x2000

System.out.println(cat1 == cat2); Meow

We can see when run the above the output will be false.
Memory

Refer to Chapter 3.2, pages 189=191 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 52


Comparing strings

Reference type does not implicitly have the ability to compare itself to
another type (besides reference) without first defining a method. To
compare them, we need to write a method to compare them.

Using == operator is testing the equivalence of the memory reference.

String cat1 = "Meow"; -> 0x1000


String cat2 = new String("Meow"); -> 0x2000

System.out.println(cat1 == cat2);

Since “new String” has returned a new allocation of a string, the


contents will be the same but the allocation is different.

Refer to Chapter 3.2, pages 189=191 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 53


Comparing strings

Reference type does not implicitly have the ability to compare itself to
another type (besides reference) without first defining a method. To
compare them, we need to write a method to compare them.

Using == operator is testing the equivalence of the memory reference.

We use .equals as this method allows a string to


String cat1 = "Meow"; -> 0x1000 compare its own contents with another. We can
define our own .equals method for our own types
String cat2 = new String("Meow"); -> 0x2000 to show define how equality is evaluated.

System.out.println(cat1.equals(cat2));

Since “new String” has returned a new allocation of a string, the


contents will be the same but the allocation is different.

Refer to Chapter 3.2, pages 189=191 (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 54


String pool

When writing our first program we have been able to define a string
literal. However java employs an intelligent but often mistaken
optimisation for strings.

String cat1 = "Meow"; -> 0x1000


String cat2 = "Meow"; -> 0x1000

If a string literal is specified, it will be added to a string pool. This


explains the behaviour we have observed on slide 50.

This allows the compiler to optimise for memory usage. The compiler
will use the same allocation and provide same reference to a string
variable of refers to the same literal.

Refer to Oracle Java Language Specification, (https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5)

The University of Sydney Page 55


Demonstration: String comparison and equality

The University of Sydney Page 56


Mutating string (Welcome StringBuilder)

Recreating a new string and deallocating the old one can be costly for
the java virtual machine (jvm).

We are able to mitigate this by using a class called StringBuilder. The


StringBuilder class contains an internal array of characters and is
mutable but does not have the same kind of affordances as String.

StringBuilder b = new StringBuilder();

The StringBuilder class allows us to assemble a string and resize the


internal char array when the number of characters exceeds the capacity
of the array.

Refer to Oracle Java SE8 API, (https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)

The University of Sydney Page 57


StringBuilder

Remember: Each time we use += with the String type we are creating a
new string. The String class is immutable and this can have great
benefits for ensuring we have a read only or for simple concatenations.

However, when it comes to complicated string manipulation or excessive


string manipulation, we will need to use

StringBuilder b = new StringBuilder();


b.append(“Hello”);
b.append(“ World”);

Refer to Oracle Java SE8 API, (https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)

The University of Sydney Page 58


Demonstration: String vs StringBuilder

The University of Sydney Page 59


See you next week!

The University of Sydney Page 60

You might also like