Download int i = 0 - Publish Web Server

Document related concepts
no text concepts found
Transcript
Computer Science 026a
Distilled
Agenda










Module 1: Introduction and Definitions
Module 2: Algorithms
Module 3: Primitive Data Types - Numeric
Module 4: Primitive Data Types - Boolean
Module 5: Iteration
Module 6: Modularity
Module 7: Object-Oriented Design
Module 8: Equivalence
Module 9: Strings
Module 10: Arrays
2
Purpose of This Review

Not a substitute for good, hard studying of your
notes.

3 hours is very little time to go over all of the material
in the course. We’ll be moving fast. Remember: this
is a review session.

Feel free to ask questions as we cover the material.

At the end, we’ll open up the floor to more in depth
questions, and revisit topics that are still unclear.
3
Computer Science 026a
Distilled
Module 1: Introduction
Definitions

Computer Science


Computing


Computing is simply problem solving – particularly problems
that deal with data.
Data



The creation and investigation of a scientific foundation for
the study of computing.
Data is just another word for information. Computer
programs process data to accomplish some task.
In a computer, data is represented by binary digits (bits): 1’s
and 0’s.
Computer

A device that executes and follows a set of instructions to
5
carry out some computing activity.
Definitions

Central Processing Unit (CPU)



Also known as the processor
Executes instructions.
Main Memory (RAM)


Internal storage that holds the
programs (instructions and data)
currently being executed by the CPU.
Volatile: information not retained when the
computer is turned off.
6
Definitions

Secondary Memory




Diskettes, hard disks, CDs, DVDs, USB sticks
Long-term (persistent) storage
for programs and other information.
Organized as files: each of which has
a file name and a folder or directory
that contains it.
Input/Output (I/O) Devices


Keyboard, mouse, screen, printer, webcam, …
Used for communicating information from the
user to the computer and the computer to the
user.
7
Definitions

Computer program



A sequence of statements which specifies how to
accomplish a particular task in a specific
programming language.
Comprised of instructions that tell the computer
what to do, and data that the computer uses to
accomplish the task at hand.
A computer will always do exactly what it is
instructed to do by a program – it does not think on
its own!
8
Definitions

Programming

The process of creating, representing, and
implementing tasks on a computer to solve a
particular problem and produce a computer
program.

Requires a language that can be translated into
machine language for the computer to execute.
9
Definitions

Programming Language


A special language that allows a computer program
to be written.
All programming languages can be classified under
one of the following types:



Compiled: A special program called a compiler
translates the program into an executable program.
Interpreted: Each line of the program is compiled on the
fly and executed as the program runs.
Hybrid: More on this later.
10
Definitions

Source code



A file (or files) containing the program written in a
high-level language (e.g. Java, C, Pascal).
Cannot be executed by the CPU (must be
translated first).
Executable (or binary) code:



A program that has been translated into machine
language code.
This translation occurs by running the source code
through a compiler or assembler.
Can be executed by the CPU.
11
Definitions

Pseudo-code




An outline of a program, written in English, that can
be easily translated into a real computer program.
Programming-language independent
Any given piece of pseudo-code can then be
translated into any number of different computer
programming languages (Java, Visual Basic, C,
C++, etc.)
Gets you to think about the logic of the problem
before worrying about the finer details of
programming.
12
Definitions

Software

Refers to computer programs. Types of software:



Operating Systems: Control the hardware and
software of a computer. Examples: Windows XP,
Linux, Mac OS.
Application Software: Word processors, spreadsheets,
web browsers.
Compilers: Translates high-level language programs
into a form (machine language) that can be executed
by the CPU.
13
Definitions

Computer network:


Internet:


A group of interconnected computers.
A world-wide interconnection of computers.
World Wide Web:


An application running on top of the Internet.
The web is not the same as the Internet.
Hosts web pages that can be viewed through a
web browser (i.e. Internet Explorer, Firefox)
14
Types of Languages

Machine language

The set of instructions that the computer’s CPU can
execute directly.

Machine dependent. Cannot execute machine
language for a PC on a Mac, and vice versa.

Difficult for programmers to use. Imagine writing a
program like this:
000100111000010100100110101111001
15
Types of Languages

Assembly language




Mnemonic representation of machine language.
Easier than machine language, but still difficult.
Assembler: Software that translates assembly
language programs into machine language.
One to one correspondence exists between
assembly language instructions and machine
language instructions.
LOAD R1, PRICE
LOAD R2, TAX
ADD R1, R2, R6
STOR R6, TOTAL
16
Types of Languages

High-level language




English-like language that makes programming
easier.
One to many correspondence exists between
high-level language instructions and machine
language instructions.
Machine-independent. A program written in Java
can be executed on a PC, and also a Mac.
High-level language program segment example:
if ((numberOfStudents) > MAX_STUDENTS) {
fullCourse = true;
}
17
von Neumann Architecture

In old computers, programs were wired directly into
the hardware.

Today’s computers are based on the “von Neumann
architecture”

Refers to a computer design model that uses a single
storage structure (main memory) to hold both
programs and data.

This storage structure is main memory; it
contains programs written in machine language and the data
for the programs.
18
von Neumann Architecture

Employs a simple fetch-execute cycle:
do
get next machine language instruction
execute the instruction
while there are no more instructions
19
The Java Language

A high-level language

Developed in the mid 1990s

Object-oriented

Portable

Java is a hybrid language. It is compiled, but not
directly into machine language. Instead, it is compiled
into an intermediate language called Java bytecode.
20
The Java Language

The Java interpreter (aka Java Virtual Machine) then
translates and executes the bytecode on the
computer, one bytecode instruction at a time.

This makes Java very portable – create one compiler,
and then create an interpreter for each platform.

Java bytecode is machine independent.
21
Computer Science 026a
Distilled
Module 2: Algorithms
What is an Algorithm

An ordered set of effective, unambiguous instructions
which, when executed, terminates.





Ordered: Steps are executed in a clear, sequential
order (one after another).
Effective: Each step is possible (can be done)
Unambiguous: There is no uncertainty as to what to do,
or how to perform the step
Terminates: The set of instructions will terminate in some
finite amount of time.
If you write a set of instructions that does not meet the
above criteria, it is not an algorithm!
23
What is an Algorithm

Once an algorithm is written, we can just blindly follow
it – we don’t have to know how it works.

A recipe is a good example of an algorithm. If
you’re baking bread, you don’t have to know how
the yeast works at a biological level. You just have
to follow the steps of the recipe as they were given
to you, and voilà! You have bread.
24
Algorithmic Constructs

Data storage/retrieval (aka input/output):


Information (data) is stored in variables so that it
can be retrieved and used later.
Pseudo-code keywords:
 GET <variable name>


REPORT <variable name>


Obtain a value (e.g. from the user) and store it in main memory
Display a value stored in main memory to the user
LET <variable name> = <value>

Store a value in a location in main memory
25
Algorithmic Constructs

Conditional execution:


Instructions may or may not be executed,
depending on some condition at time of execution
(run time).
Pseudo-code keywords:

IF-THEN


Decides whether or not some sequence of instructions will be
executed
IF-THEN-ELSE:

Selects one of two sequences of instructions to be executed
26
Algorithmic Constructs

Repetition:



A sequence of instructions is executed
0, 1, or more times
Also called a loop
Pseudo-code keywords:



WHILE
FOR
DO-WHILE
27
Feeling Loopy Yet?

There are 2 types of loops:

Pre-tested:


Body executed 0 or more times
Two main forms:

FOR <number of repetitions> DO
<loop body statements>

WHILE <condition>
<loop body statements>
END WHILE
28
Feeling Loopy Yet?

Post-tested:


Loop body executed 1 or more times
Continues to repeat the execution of the
<loop body statements> as long as <condition> is
true
DO
<loop body statements>
WHILE <condition>
29
Feeling Loopy Yet?

Other ways to classify loops:

Deterministic (Definite): We know before the loop
starts how many times it will execute.


The for loop is deterministic.
Non-Deterministic (Indefinite): We cannot know
before the loop starts how many times it will
execute. It just loops until its condition becomes
false.

The WHILE and DO…WHILE loops are nondeterministic.
30
From Pseudo-code to Java

Data storage/retrieval

REPORT
System.out.println("The average of the numbers is " +
(float) sum / howmany);

GET

Consists of two Java statements:
a prompt statement and an input statement
System.out.print("Please enter number " + i + ": ");
aNumber = Integer.parseInt(keyboard.readLine());
31
From Pseudo-code to Java

Data storage/retrieval (cont’d)

LET
int howmany=3;

= is the assignment operator; it does not represent
equality in the mathematical sense!
32
From Pseudo-code to Java

Conditional execution

IF-THEN-ELSE
if (jeffShutsUp == true) {
System.out.println(“Hurray!”);
}
else if (jeffFaints == true) {
System.out.println(“Haha!”);
}
else {
System.out.println(“Boo!”);
}

Note: If more than one statement appears below the
if or the else, they must be enclosed in braces.
33
From Pseudo-code to Java

Repetition

FOR howMany REPETITIONS
for (int i = 0; i < howMany; i++) {
System.out.println(“Hello!”);
}

Note: If more than one statement appears below the
for, they must be enclosed in braces.
34
From Pseudo-code to Java

Repetition

WHILE
int i = 0;
while (i < 10) {
System.out.println(“Hello!”);
i++;
}

Note: If more than one statement appears below the
while, they must be enclosed in braces.
35
From Pseudo-code to Java

Repetition

DO…WHILE
int i = 0;
do {
System.out.println(“Hello!”);
i++;
} while (i < 10);

Note: If more than one statement appears between
the do and the while, they must be enclosed in
braces.
36
From Pseudo-code to Java

Each Java file has to have the same name (casesensitive) as the class it contains.
public class Test { . . . }


This would have to be in a file named Test.java
To compile this class, we use javac:
javac Test.java

This produces the file Test.class – our compiled
bytecode. To run this program, we use java:
java Test
37
Stepwise Refinement





The process of breaking a problem down into smaller
sub-problems.
Each sub-problem is implemented in a separate
module.
The main algorithm then uses each module to
accomplish its task.
We say that the main algorithm is at the highest level
of abstraction, while modules are at lower levels.
This all leads to the notion of modularity, which makes
our code easier to modify, maintain, and reuse.
38
Computer Science 026a
Distilled
Module 3: Primitive Data Types - Numeric
Primitive Types


Store simple data values. Primitives can only store 1
value at a time. If we assign a value to a primitive
type, it overwrites (replaces) the value that was
already there.
Type of primitives:



Integers (int)
 …, -2, -1, 0, 1, 2, …
Real numbers (float, double)
 …, -2.12, -2.101, -1.999, 0.0, 1.5, 2.2789, …
Booleans (boolean)
 true or false
40
Primitive Types

The values stored in primitives are called literals
 -1 is an integer literal
 112.0 is a floating-point literal
 true is a boolean literal

Each different primitive type is represented in memory
in a different way. So, we have to declare the types of
our variables so that compiler knows how to represent
our variable in memory.
41
Primitive Types


Declaring a variable: Reserving a named space in
main memory where a value will be stored, and
explicitly specifying its data type.
Syntax:
<type> <variableName>;

Example:
int myInteger;
42
Primitive Types

int

Used to store integral values
 Stored in 32 bits
 Can store numbers up to approx. 2 billion
long

Used to store larger integral values
 Stored in 64 bits
byte, short




Used to store smaller integral values
Stored in 8 bits and 16 bits, respectively
43
Primitive Types

float

Used to store smaller floating point values
 Stored in 32 bits
 Has a precision of approximately 7 digits
double





Used to store larger floating point values
Stored in 64 bits
Has a precision of approximately 15 digits.
Used more commonly in Java to avoid rounding
errors
44
Java Arithmetic Operators




Addition: +
Subtraction: Multiplication: *
Division: /




When performed on integers, returns an integer
 9 / 2 = 4 (not 4.5!)
When performed on doubles, returns a double
 9.0 / 2.0 = 4.5
When performed on a mix of both, returns a double
 9.0 / 2 = 4.5
Modulus: %

Remainder of a division
 12 % 7 = 5
45
Precedence Rules

Java evaluates arithmetic expressions in the
same order as we do normally in mathematics:




Parentheses
Multiplication, division, modulus from left to right
Addition, subtraction from left to right
Examples:



12 + 6 % 5 = 13
10 + 2 % 5 / 3 = 10
10 + 2 % 5 / 3.0 = 10.66…
46
Named Constants

Magic Numbers:

A number in source code that means something to
the programmer, but looks like gibberish to other
readers. Example:
if (i == 28) {
System.out.println(“Hello!”);
}


The reader is left wondering: what does the 28
represent?
Solution: named constants!
47
Named Constants

We can declare a named constant using the keyword
final to make the code more readable:
final int HELLO_MENU_OPTION = 28;
if (i == HELLO_MENU_OPTION) {
System.out.println(“Hello!”);
}


Constants must be declared and assigned in the same
line. After they are declared, they cannot be changed
at a later time. They are constant.
Convention is to use capital letters and separate
words by underscores.
48
Assignment Rules

An integer value can be assigned to:
int i = 5;
 An integral variable type
double i =
 A floating point variable type
5;

A floating point value can only be assigned to a
floating-point variable type
double i = 5.0;

However, we can “cheat” and change a value’s type
by typecasting it. For example:
int i = (int)5.4;

i will now store the value 5
49
Computer Science 026a
Distilled
Module 4: Primitive Data Types - Boolean
Conditional Execution

Recall that our if statements have the
following form:
if ( <condition> )
statement;

<condition> is nothing more than a Boolean
expression (an expression that evaluates to true or
false)


If it is true, then statement is executed.
If it is false, then statement is not executed.
51
Comparison Operators

Boolean expressions compare values using relational
operators:
Operator Description
Example
<
Less than
if (x < 10)
>
Greater than
while (y > 5)
==
Equal
if (z == 1)
<=
Less Than/Equal
if (w <= 100)
>=
Greater Than/Equal while (j >= 0)
!=
Not Equal
if (k != 50)
52
Logical Operators

Boolean expressions can be combined using the
logical operators:
Operator Description Example

!
Not
if (!isClassOver)
&&
And
if ((x > 5) && (x < 10))
||
Or
while ((x < 0) || (x > 2))
Although not explicitly required, good style dictates
that we should put parentheses around each individual
condition, as well as around the entire compound
condition.
53
Logical Operators

Truth table for the logical operators:
A
A&&B
A||B
true false
true
true
true false false
false
true
false true
true
false
true
false false true
false
false
true
B
!A
54
Logical Operator Precedence

Java evaluates logic operators according to the
following precedence:





Parentheses
! (Negation)
&& (AND)
|| (OR)
Example:
 A || B && !C
evaluates as
A || (B && !C)
55
Primitive Type: boolean


In Java, boolean is a primitive type that have can a
value of either true or false.
We can declare variables of type boolean and
assign values to them:
boolean isThisOverYet = false;

Shortcut: when using boolean variables in conditions,
we can say:
if (isThisOverYet)

This is equivalent to:
if (isThisOverYet == true)
56
Nested If Statements

if statements can be nested within other if
statements:
if (age >= 16)
if (hasLicense)
System.out.println(“Turn on the car!”);
else
System.out.println(“Sorry, go get a license!”);
else
System.out.println(“You’re not even old enough!”);

Notice that we don’t need braces in this case. This is
because an entire if-else block is considered to be
one statement.
57
The Evil Dangling Else

Consider the following code:
if (age >= 16)
if (hasLicense)
System.out.println(“Turn on the car!”);
else
System.out.println(“You’re not even old enough!”);

Problem: Do we associate the else with the outer if
statement, or the inner if statement? We call this the
dangling else problem.
58
The Evil Dangling Else


Solution: Java implements the dangling else
rule. This rule states that an else will be associated
with the nearest if statement.
So, in the previous example, the else will be
associated with the inner if statement:
if (age >= 16)
if (hasLicense)
System.out.println(“Turn on the car!”);
else
System.out.println(“You’re not even old enough!”);

Result: Not what we wanted!
59
The Evil Dangling Else

Solution: Use braces to explicitly tell Java the
if statement with which the else should be
associated.
if (age >= 16) {
if (hasLicense)
System.out.println(“Turn on the car!”);
}
else
System.out.println(“You’re not even old enough!”);
60
Switch Statement


Sometimes, we have so many conditions to test that
we have a long chain of if-else statements.
We can use a switch statement to replace this chain:
if (month == 1) {
switch (month) {
…
case 1:
}
case 3:
else if (month == 2) {
…
…
break;
}
case 2:
.
…
.
break;
.
}
61
Switch Statement

Case values must be integers

We can put multiple cases above the same block of
code.

The default case is equivalent to an else
statement. If no other cases match, then the code
under the default case is executed.

Important: every case must end with a break!
62
Switch Statement - Example
switch (menuOption) {
case 1:
System.out.println(“Rock, Paper, Scissors)
break;
case 2:
System.out.println(“One Two Penny Pickup”);
break;
case 3:
System.out.println(“Quit!”);
break;
default:
System.out.println(“Invalid choice, please try again.”);
break;
}
63
Computer Science 026a
Distilled
Module 5: Iteration
Control Structures

Statements are executed in sequential order.

Problem: How to execute statements multiple times?
Solution: Use a loop!


Java has 3 loop structures:
 for (pre-tested, deterministic)
 while (pre-tested, non-deterministic)
 do…while (post-tested, non-deterministic)
65
The for Loop
for (<initialization>; <condition>; <iteration>)
<body>

<initialization>: Performed once before loop begins

<condition>: Checked before loop starts and after the
end of each iteration. Loop starts/continues as long as it is
true.

<iteration>: Performed at the end of each iteration

<body>: Statement performed each iteration.
66
The for Loop

Example: Executing a statement 3 times.
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);

Let’s examine the flow of execution
67
The for Loop
Declare a variable i and set it to 0
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
i: 0
68
The for Loop
Check: is i less than 3?
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
i: 0
69
The for Loop
Yep, let’s execute the loop!
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
i: 0
70
The for Loop
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 0
71
The for Loop
Increment i by 1
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 1
72
The for Loop
Check: is i less than 3?
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 1
73
The for Loop
Yep, let’s execute the loop!
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 1
74
The for Loop
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 1
This is iteration 1
75
The for Loop
Increment i by 1
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 2
This is iteration 1
76
The for Loop
Check: is i less than 3?
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 2
This is iteration 1
77
The for Loop
Yep, let’s execute the loop!
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 2
This is iteration 1
78
The for Loop
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 2
This is iteration 1
This is iteration 2
79
The for Loop
Increment i by 1
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
80
The for Loop
Check: is i less than 3?
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
81
The for Loop
No sir, we’re moving on!
for (int i = 0; i < 3; i++)
System.out.println(“This is iteration “ + i);
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
82
The while Loop
while (<condition>)
<body>

<condition>: Checked before loop starts and after the
end of each iteration. Loop starts/continues as long as it is
true.

<body>: Statement performed each iteration.

Note: The body needs to contain a statement that will
eventually make the condition false. Otherwise, we will
have what is known as an infinite loop.
83
The while Loop

Example: Executing a statement 3 times.
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}

Let’s examine the flow of execution
84
The while Loop
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
i: 0
85
The while Loop
Check: Is i < 3?
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
i: 0
86
The while Loop
Yep, let’s execute the loop!
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
i: 0
87
The while Loop
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 0
88
The while Loop
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 1
89
The while Loop
Check: Is i < 3?
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 1
90
The while Loop
Yep, let’s execute the loop!
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 1
91
The while Loop
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 1
This is iteration 1
92
The while Loop
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 2
This is iteration 1
93
The while Loop
Check: Is i < 3?
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 2
This is iteration 1
94
The while Loop
Yep, let’s execute the loop!
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 2
This is iteration 1
95
The while Loop
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 2
This is iteration 1
This is iteration 2
96
The while Loop
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
97
The while Loop
Check: Is i < 3?
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
98
The while Loop
No sir, we’re moving on!
int i = 0;
while (i < 3) {
System.out.println(“This is iteration “ + i);
i++;
}
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
99
The do…while Loop
do
<body>
while ( <condition> );

<condition>: Checked after the loop has executed once,
and after each subsequent iteration. Loop continues as
long as it is true.

<body>: Statement performed each iteration.

Note: The body needs to contain a statement that will
eventually make the condition false. Otherwise, we will
100
have what is known as an infinite loop.
The do…while Loop

Example: Executing a statement 3 times.
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);

Let’s examine the flow of execution
101
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Output:
i: 0
102
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Output:
This is iteration 0
i: 0
103
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Output:
This is iteration 0
i: 1
104
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Check: Is i < 3?
Output:
This is iteration 0
i: 1
105
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Yep, let’s execute the loop!
Output:
This is iteration 0
i: 1
106
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Output:
This is iteration 0
i: 1
This is iteration 1
107
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Output:
This is iteration 0
i: 2
This is iteration 1
108
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Check: Is i < 3?
Output:
This is iteration 0
i: 2
This is iteration 1
109
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Yep, let’s execute the loop!
Output:
This is iteration 0
i: 2
This is iteration 1
110
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Output:
This is iteration 0
i: 2
This is iteration 1
This is iteration 2
111
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
112
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
Check: Is i < 3?
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
113
The do…while Loop
int i = 0;
do {
System.out.println(“This is iteration “ + i);
i++;
} while (i < 3);
No sir, we’re moving on!
Output:
This is iteration 0
i: 3
This is iteration 1
This is iteration 2
114
Computer Science 026a
Distilled
Module 6: Modularity
Benefits of Modularity

By breaking up a problem into modules, we make it
easier to modify and maintain


Don’t have to spend time wading through mountains of
code; just edit the module containing the code to be
changed
Allows for easier code reuse



Modules can be designed generically so that they are
applicable to many different programs. We can then just
“plug them in” to new applications as needed
Result: Less time spent developing code!
116
Corollary: More time spent sleeping!
Modularity in Java

In Java, there are 3 main types of modules:

Packages
 Contain related sets of classes

Can be imported into a program and used, achieving code
reuse

Example:



Recall the line from your Java programs: import java.io.*;
java.io is a package containing many different classes (including
BufferedReader)
The asterisk means that we want to import all classes in the
java.io package
117
Modularity in Java

Classes
 A collection of related data (state) along with methods
(behaviour) to act upon that data

Variables of class types are called reference variables
This is in contrast to variables of primitive types, which are
called simple variables

Example:



BufferedReader is a class you used in your assignments to
retrieve input from the user.
More on classes later
118
Modularity in Java

Methods
 Contained within classes
 Implement the behaviour of a class; that is, they perform
actions (like calculating how much longer I’m going to talk)

Example:



The BufferedReader class has a method with which you are all
familiar: readLine();
It waits for the user to enter data and press Enter. Upon doing so, it
returns the String entered by the user.
Another Example:

The main method is a method.

It is a special method that serves as the starting point of every
program.
119
Methods

Two types of methods:

Static methods:




Defined by using the keyword static in the method definition:
Recall: public static void main(String[] args)
Called on a class – not on an object:
 Math.abs(-1);
 Here, we’re using the class name (Math) – not the name of a
variable.
However, if we’re invoking (calling) static methods that exist in the
same class, we don’t need to specify the class name
 Recall from assignment #3: searchForCompany(company);

This is a static method, but since we’re calling it from the same
class, we don’t need to say: TestPopcorn.searchForCompany
120
Methods

Two types of methods:

Instance methods:

Defined without the keyword static in the method definition:
public void setCompanyName(String newName)

Called on an object – not on a class

// instantiate (create) a new Person object
Person me = new Person(“Jeff”);
// method is called on variable me – not on the Person class
me.setEyeColour(“Green”);

More on these methods a bit later
121
Defining a Static Method

Syntax:
public static <return type> <method name> ( <formal parameters> )



<return type>: The type of the value returned by the class.
Some possible types:
 int, String, double, float
 void – Class doesn’t return anything
<method name>: An identifier associated with the method that
will be used to call it.
<formal parameters>: A list of variable types that the
method expects callers to pass in, along with names that will be
used for those variables in the method.
122
Defining a Static Method

Example:
public static double getAverage(int num1, int num2, int num3) {
return (double)(num1 + num2 + num3) / 3;
}

getAverage is the name we will use to call this method

This method expects callers to pass in 3 integer variables

It returns a value of type double – the average of values of the
3 parameters


How do we know what it returns?
Is it because of the return statement?
123
Invoking a Static Method

Example:
public static double getAverage(int num1, int num2, int num3) {
return (double)(num1 + num2 + num3) / 3;
}
public static void main (String[] args) {
double avg = getAverage(1,2,3);
}



We invoke a static method by using its name followed by
parentheses. If the method takes parameters, we put the values
we’re passing into the method in the parentheses.
Actual parameters: The values we’re passing in
Formal parameters: The value types expected by the method
124
(the contract of the method)
Formal vs. Actual Parameters

Formal parameters:




The contract of the method
The method definition says, “Hey! It you want to call me, this is
what you’re going to have to give me!”
If you pass in variables of types that are not defined in the formal
parameters of the method, you get a compile error.
Actual parameters:

The actual values that you pass into the method. These could be
literals (-1, 1.201, etc.), constants (MAX_AGE), or variables
(myAge)
125
Formal vs. Actual Parameters

Example:
/* This method declares 3 integers as its formal parameters.
It will
* refer to them using the identifiers num1, num2, and num3 in the
* method body. */
public static double getAverage(int num1, int num2, int num3) {
return (double)(num1 + num2 + num3) / 3;
}
public static void main (String[] args) {
// 1, 2, and 3 are the actual parameters
double avg = getAverage(1,2,3);
/* Compile error! Not only does getAverage not allow Strings, but
* it requires 3 parameters! */
double avg2 = getAverage(“1”);
}
126
Passing Parameters

Passing by value


When we pass primitive variable types (int, float,
double, boolean, etc.) into a method, we pass them by
value.
This means that a copy of the variables get passed – not the
variables themselves.
public static void doSomething(int myParameter) {
myParameter = 4;
}
public static void main (String[] args) {
int i = 5;
doSomething(i);
// What will i equal here?
}
127
Passing Parameters

Passing by reference

When we pass class variable types (Rectangle, Person,
etc.) into a method, we pass them by reference.

This means that the objects themselves get passed – not
copies of the objects.
public static void doSomething(Person p) {
p.setName(“Jeff”);
}
public static void main (String[] args) {
Person me = new Person(“Bob”);// create a new Person named Bob
doSomething(me);
// What will me equal here?
}
128
Method Overloading

Defining multiple methods with the same name in the
same class.
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max (double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
129
Method Overloading

Each overloaded method has to take different parameters.
Either:



Different parameter types
A different number of parameters
Different parameter types and a different number of parameters.
public static int max(int num1, int num2) { … }
public static double max (int num1, int num2) { … }
public static void main(String[] args) {
/* Java has no way to know which version of max you want to call
* since both version takes 2 integer parameters */
double d = max(1,2);
}
130
Method Prototypes

The prototype of a method is comprised of the following
information:




Return type
Method Name
Number and types of parameters
A few method prototypes
public static int max(int num1, int num2)
public static double max (int num1, int num2)
public static float max(float num1, float num2)

A method’s prototype is also called its signature
131
Computer Science 026a
Distilled
Module 7: Object-Oriented Design
Object-Oriented Design

Java is considered an object-oriented programming
language


Everything we wish to model in the program can be represented
by an object.
Objects have:



A type (i.e. Person, Rectangle, …)
Properties (i.e. Hair colour, height, weight, ...)
Behaviour (i.e. speak(), eat(), run(), walk(), …)
133
Classes

Class

Formal definition: Collection of data (state / properties) and
methods (behaviour) that act upon that data.

Informal definition: A blueprint that defines a group of objects that
have common attributes and behaviours.
134
Classes

For example, think back to high school biology when you learned
about biological classes

The canine is a class of mammals that have common state and
behaviour:


State: 4 legs, 1 tail, fur
Behaviour: bark, run, howl, yelp, sleep, eat

Each individual dog (instance of the canine class) will have these
attributes and behaviours.

However, they will be distinct “objects”, and will have different
state values. One dog might have brown fur, while the other has
white fur.
135
Classes vs. Objects

Consider a blueprint of a house.




We cannot open the blueprint’s door,
or close the blueprint’s window.
It is not a concrete house, but merely
an abstract representation of a
house.
But we can create as many houses
as well like based on the blueprint.
Each house will share common
attributes since the same blueprint
was used.
The blueprint is analogous to a
class.
The houses are instances
(objects) of the class.
136
Types of Classes

Pre-defined Classes:




The Java API
Other classes written by other programmers / companies.
Reduce development time since code is already written
Three pre-defined classes we have seen in class:




Math
Rectangle
String
User-defined Classes:


These are classes that you create yourself.
In assignment #3, you created the PopcornCompany class.
Because you wrote it yourself (hopefully!), we call it a user137
defined class.
Defining a Class in Java
public class <classname> {
}

For example, we might define a Person class:
public class Person {
}

We are then required to save this class in a file named
Person.java.
138
Instance Variables

Each object has its own attributes:


Fred is 175 cm tall, weighs 70 kg, and is 20 years old.
Jane is 150 cm tall, weighs 45 kg, and is 23 years old.

Attributes are represented by instance variables in a
class.

Instance variables are normal variables that are declared
in a class, but outside of any method.

Every object then has its own set of instance variables in
which it stores its attributes (state).
139
Instance Variables

Let’s add name and age instance variables to our
Person class:
public class Person {
private String name;
private int age;
}


Notice that our instance variables are declared inside the
class body, but outside of any method body.
We use the keyword private when declaring them to
prevent any outside classes from accessing/modifying
them directly.
140
Instance Methods

Instance methods are used to model the behaviour of an
object.

They are called on objects – not on classes



Person.setName(“Jeff”);
myPerson.setName(“Jeff”);
// bad! Person is a class
// good! myPerson is an object
They are declared exactly the same way as static
methods, except without the static keyword:
public <return type> <method name> ( <formal parameters> )
141
Instance Methods

We classify instance methods as one of two types:

Accessor Methods:
 Retrieve (access) data from the object’s instance variables
 Do not change the object’s state
 Examples:



getName()
getAge()
Mutator Methods:
 Change (mutate) data in the object.
 Generally do not return anything.
 Examples:


setName(String newName)
setAge(int newAge)
142
Instance Methods

Let’s start by adding getName() and getAge() accessor
methods to our Person class:
public class Person {
public int getAge() {
private String name;
private int age;
return age;
}
} // end of class
public String getName() {
return name;
}



Notice the return types on our accessor methods – they
correspond with the types of the variables they access.
There is no static keyword on instance methods.
143
No data is being changed; it is simply returned to the user.
Instance Methods

Now we need a way to change the object’s state. We’ll
declare setName() and setAge() mutator methods:
public class Person {
public void setAge(int age) {
private String name;
private int age;
this.age = age;
}
// accessor methods omitted
public void setName(String name) {
} // end of class
this.name = name;
}


Notice the parameter types on our mutator methods – they
correspond with the types of the variables they change.
No data is being returned, so the return value is void.
144
Instance Methods

Notice in our mutator methods that we used the keyword this.

Because the parameter names are the same as the instance
variable names, we have to use the keyword this to distinguish
between the two.
this.name refers to the instance variable name.

public class Person {
public void setAge(int age) {
private String name;
private int age;
this.age = age;
}
// accessor methods omitted
public void setName(String name) {
} // end of class
this.name = name;
}
145
Constructors


Now we have data and methods, but we also want a way to
initialize our Person objects with some data upon creating them.
To do this, we can declare one or more constructors:

Special methods that have the same name as the class

No return value

Can take 0 or more parameters, just like any other method

Not called directly by the programmer – Java calls the constructor
when the object is created using the new keyword

Parameters to constructors are normally the initial values for the
146
object
Constructors


A constructor that takes no parameters is called the default
constructor. It generally initializes the object to some predefined set of default values.
For example, a default constructor for our Person object might
look something like this:
public class Person {
private String name;
private int age;
public Person() {
this.name = “NO NAME”;
this.age = 0;
}
}
147
Constructors

The default constructor would be called if we created a new
Person object using the following code:
Person p = new Person();

What would the following output?
Person p = new Person();
System.out.println(p.getName());


Answer: The string “NO NAME”
Why? Because our default constructor was coded to
initialize the Person object’s name to “NO NAME”.
148
Constructors


We usually overload constructors (specify multiple constructors,
each taking different types and/or numbers of parameters).
Let’s create a more useful constructor that takes a name and
age as parameters:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// mutators and accessors omitted
}
149
Constructors

We can now create and initialize a new Person object all in our
line:
Person p = new Person(“John”,12);

What would the following output?
Person p = new Person(“John”,12);
System.out.println(p.getName());

Answer: The string “John”
150
Computer Science 026a
Distilled
Module 8: Equivalence
Identity vs. State

Let’s see what insight Mary-Kate and Ashley Olsen can
offer to help clarify the finer subtleties of identity and
state in the context of object-oriented programming.
152
Identity vs. State
153
Identity vs. State
154
Identity vs. State
155
Identity vs. State
I have sandy blonde hair!
156
Identity vs. State
Like, so do I!
157
Identity vs. State
I have blue eyes!
158
Identity vs. State
Whoa! Me too!
159
Identity vs. State
We have state equality!
We have state equality!
160
Identity vs. State
But I’m not the same
person as her!
161
Identity vs. State
Ewww! No way!
162
Identity vs. State
We don’t have identity
equality!
We don’t have identity
equality!
163
Identity vs. State

Thanks, ladies. We’ll take it from here.

Recall: == is the equality operator

For primitive types, == is unambiguous; it just compares two
variables to see if they store the same value.
int i = 5;
int j = 5;
if (i == j)
System.out.println(“They’re equal!”);
164
Identity vs. State

For reference types, however, we have 2 different types of
equality:

State: The data contained in the reference types are the same.


Mary-Kate and Ashley both had the same state (hair colour, eye
colour). In other words, they had the same instance variables.
Identity: The reference types point to the same object.

Mary-Kate and Ashley are two different objects. They do not point to
the same Person object, so they do not have identity equality.
165
Identity vs. State

Example of Identity Equality:
Person p = new Person(“John”,12);
Person q = p;

The first line creates a new Person object.

The second line merely creates a new variable that points to the
Person object created in the first line.

These variables have identity equivalence.

A change made in one (i.e. by calling a mutator method) will
affect the other variable since they both point to the same object.
166
Identity vs. State

When dealing with reference types, the equality operator (==)
compares identity equality.
Person p = new Person(“John”,12);
Person q = p;
if (p == q)
System.out.println(“They’re equal!”);

Line 3 will evaluate to true since they point to the same object.
167
Identity vs. State

If we want to check state equality, we need to use the
equals() method:
Person p = new Person(“John”,12);
Person q = new Person(“John”,12);
if (p.equals(q))
System.out.println(“They’re equal!”);

Line 3 will evaluate to true since they have the same state, even
though they point to different objects in memory.
168
Computer Science 026a
Distilled
Module 9: Strings
What is a String?

A string is simply a sequence of characters – a combination of
any of the following:





In Java, a string literal is enclosed in quotes (but the
quotes are not part of the string – they merely delimit it!)


Letters
Numbers
Symbols
Spaces
“Hello, World!”
When we use strings in Java, we’re actually using objects
of the String class (defined in the Java API)
170
Using Strings


Normally, we need to use the keyword new to create a new
object
The String class, however, is special. We can use string literals
without having any object:
System.out.println(“Hello, world!”);

We can declare String variables without using the keyword new
(we could technically create them using the new keyword if we
wanted to):
String myString = “Hello, world!”;

Despite these differences, String variables are still reference
variables; that is, they point to objects in memory
171
Using Strings

If we want to clear a String variable, we can assign to it the
empty string:
String myStr = “”;

We could check a String’s length using the length() method:
System.out.println( myStr.length() );

We could convert all letters in a String to uppercase:
myStr = myStr.toUpperCase();
172
Changing Strings



Strings are said to be immutable. This means that they cannot
be changed. Every method in the String class returns a new
String object – it does not modify the String on which the method
was invoked.
But sometimes we want to change the values of String variables!
No problem, just change the reference:
myStr = myStr.toUpperCase();

toUpperCase() returns a new String object, so we just assign
that object to our reference variable myStr, and now that
variable points to the uppercase String instead of the original
one.
173
Changing Strings

Example:
String myStr = “Hello!”;
myStr = myStr.toUpperCase();

Memory:
myStr

myStr is declared but currently doesn’t point to anything
174
Changing Strings

Example:
String myStr = “Hello!”;
myStr = myStr.toUpperCase();

Memory:
Hello!
myStr

A String object containing the text “Hello!” is created in memory.
175
Changing Strings

Example:
String myStr = “Hello!”;
myStr = myStr.toUpperCase();

Memory:
Hello!
myStr

The String object is assigned to myStr, so myStr now points to
the String.
176
Changing Strings

Example:
String myStr = “Hello!”;
myStr = myStr.toUpperCase();

Memory:
myStr

Hello!
HELLO!
myStr.toUpperCase() is executed, which creates a new
uppercase String in memory.
177
Changing Strings

Example:
String myStr = “Hello!”;
myStr = myStr.toUpperCase();

Memory:
myStr

Hello!
HELLO!
The uppercase String is assigned to myStr, so myStr now points
to that new String
178
Changing Strings

Example:
String myStr = “Hello!”;
myStr = myStr.toUpperCase();

Memory:
myStr

Hello!
HELLO!
Notice that the original String was never changed. We just
changed what myStr pointed to.
179
Conversions

String to Integer
String myStr = “94”;
int i = Integer.parseInt(myStr);

String to Double
String myStr = “94.59”;
double d = Double.parseDouble(myStr);

Any numeric type to String
double d = 94.59;
String myStr = “” + 94.59;
180
State vs. Identity with Strings

When comparing state and equality, Strings don’t act like other
reference types


You should have the feeling by now that String is a special class!
Strings are said to be interned. This means that when we
create new Strings that have the same value as a String that
was already created, Java is smart enough to say, “Hey! I
already have that String in memory! I’ll just point you to that
one, and save myself the trouble of creating a new one!”
String str1 = “TEST”;
String str2 = “TEST”;

Even though these look like two different objects, Java really just
pointed the second variable to the object pointed to by the first
one. Thus, they are both state and identity equal.
181
State vs. Identity with Strings

We can circumvent interning with Strings by using the new
keyword:
String str1 = new String(“TEST”);
String str2 = new String(“TEST”);

Now we’ve forced Java to create two separate objects. They
are now state equal, but not identity equal.
182
Computer Science 026a
Distilled
Module 10: Arrays
Arrays of Primitive Types

Recall: variables of primitive and reference types can store only
one value at a time.

What if we want to store a collection of values together?

Answer: We use arrays!

Array:


Collection of data items (values) of the same type
An array is an object – it is a reference type


An array of integers
An array of doubles
184
Arrays of Primitive Types

Declaring an array
type[] variableName = new type[size];

Example: An array that can store 17 integers
int[] grades = new int[17];

The identifier grades refers to the entire array (collection) of
integers – not just one in particular.

Once an array has been declared, its size is fixed. We cannot
change it.
185
Arrays of Primitive Types

Another way to declare an array:
type[] variableName = { firstValue, secondValue, … };

Example: An array that can store 5 integers
int[] grades = { 94, 76, 92, 83, 91 };

The size of the array is inferred from the initializer list.
186
Arrays of Primitive Types

Indexing an Array:

Elements of an array are numbered from 0 to ARRAY_SIZE – 1
int[] grades = { 94, 76, 92, 83, 91 };

This creates the following array in memory. The indices of the array
listed above each element:
0
1
2
3
4
94 76 92 83 91

To access a specific array element, use the array name and the
index in square brackets:
int i = grades[0];
// assigns 94 to i
187
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
0
188
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
We’re okay!
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
0
189
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
0
190
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
1
191
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
We’re okay!
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
1
192
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
1
193
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
2
194
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
We’re okay!
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
2
195
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
2
196
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
3
197
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
We’re okay!
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
3
198
Arrays of Primitive Types

Looping Through an Array:
int[] grades = { 94, 76, 92 };
for (int i = 0; i <= grades.length; i++) {
System.out.println(grades[i]);
}
0
1
2
94 76 92
i
3
199
Arrays of Primitive Types

We went past the end of the array!

Have to be very careful that we check our loop conditions when
iterating through arrays.

In this case, the condition in the for loop should have been
“less than”, rather than “less than or equal to”
for (int i = 0; i


<
grades.length; i++)
Seems like an innocent problem, but it will crash your program.
What if you were writing software for handling a space shuttle
launch? Moral: bugs really do have real world consequences!
200

And that, ladies and gentlemen, is the end of our review.
201





The final exam is this Friday night (June 9th, 2006) from
7 PM – 10 PM in MC 320 (our classroom)
Bring a few pencils, an eraser, your student card, and yourself.
The exam is closed book, and no reference materials are
allowed.
Be sure to turn off all cell phones and pagers before entering the
classroom (better yet: leave ‘em at home!)
Jeff will be in the lab tomorrow from 5 PM – 7PM for last minute
questions and groveling. 
202