Title: Computer Science 026a
1Computer Science 026a
Distilled
2Agenda
- 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
3Purpose 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. Well be moving fast.
Remember this is a review session. - Feel free to ask questions as we cover the
material. - At the end, well open up the floor to more in
depth questions, and revisit topics that are
still unclear.
4Computer Science 026a
Distilled
Module 1 Introduction
5Definitions
- Computer Science
- The creation and investigation of a scientific
foundation for the study of computing. - Computing
- Computing is simply problem solving
particularly problems that deal with data. - Data
- 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) 1s and 0s. - Computer
- A device that executes and follows a set of
instructions to carry out some computing
activity.
6Definitions
- 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.
7Definitions
- 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 directorythat 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.
8Definitions
- 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!
9Definitions
- 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.
10Definitions
- 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.
11Definitions
- 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.
12Definitions
- 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.
13Definitions
- 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.
14Definitions
- Computer network
- A group of interconnected computers.
- Internet
- 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)
15Types of Languages
- Machine language
- The set of instructions that the computers 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
16Types 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, PRICELOAD R2, TAXADD R1, R2, R6STOR
R6, TOTAL
17Types 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
18von Neumann Architecture
- In old computers, programs were wired directly
into the hardware. - Todays 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.
19von Neumann Architecture
- Employs a simple fetch-execute cycle
- do
- get next machine language instruction execute
the instruction - while there are no more instructions
20The 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.
21The 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.
22Computer Science 026a
Distilled
Module 2 Algorithms
23What 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!
24What is an Algorithm
- Once an algorithm is written, we can just blindly
follow it we dont have to know how it works. - A recipe is a good example of an algorithm. If
youre baking bread, you dont 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.
25Algorithmic 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
- Obtain a value (e.g. from the user) and store it
in main memory - REPORT
- Display a value stored in main memory to the user
- LET
- Store a value in a location in main memory
26Algorithmic 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
27Algorithmic Constructs
- Repetition
- A sequence of instructions is executed 0, 1, or
more times - Also called a loop
- Pseudo-code keywords
- WHILE
- FOR
- DO-WHILE
28Feeling Loopy Yet?
- There are 2 types of loops
- Pre-tested
- Body executed 0 or more times
- Two main forms
- FOR DO body statements
- WHILE
-
- END WHILE
29Feeling Loopy Yet?
- Post-tested
- Loop body executed 1 or more times
- Continues to repeat the execution of the body statements as long as is true
- DO WHILE
30Feeling 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 DOWHILE loops are
non-deterministic.
31From Pseudo-code to Java
- Data storage/retrieval
- REPORT
- GET
- Consists of two Java statements a prompt
statement and an input statement
System.out.println("The average of the numbers is
" (float) sum /
howmany)
System.out.print("Please enter number " i "
")aNumber Integer.parseInt(keyboard.readLine()
)
32From Pseudo-code to Java
- Data storage/retrieval (contd)
- LET
- is the assignment operator it does not
represent equality in the mathematical sense!
int howmany3
33From Pseudo-code to Java
- Conditional execution
- IF-THEN-ELSE
- Note If more than one statement appears below
the if or the else, they must be enclosed in
braces.
if (jeffShutsUp true) System.out.println(
Hurray!) else if (jeffFaints true)
System.out.println(Haha!) else
System.out.println(Boo!)
34From Pseudo-code to Java
- Repetition
- FOR howMany REPETITIONS
- Note If more than one statement appears below
the for, they must be enclosed in braces.
for (int i 0 i System.out.println(Hello!)
35From Pseudo-code to Java
- Repetition
- WHILE
- Note If more than one statement appears below
the while, they must be enclosed in braces.
int i 0 while (i System.out.println(Hello!) i
36From Pseudo-code to Java
- Repetition
- DOWHILE
- Note If more than one statement appears between
the do and the while, they must be enclosed in
braces.
int i 0 do System.out.println(Hello!)
i while (i
37From Pseudo-code to Java
- Each Java file has to have the same name
(case-sensitive) as the class it contains. - This would have to be in a file named Test.java
- To compile this class, we use javac
- This produces the file Test.class our compiled
bytecode. To run this program, we use java
public class Test . . .
javac Test.java
java Test
38Stepwise 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.
39Computer Science 026a
Distilled
Module 3 Primitive Data Types - Numeric
40Primitive 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
41Primitive 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.
42Primitive Types
- Declaring a variable Reserving a named space in
main memory where a value will be stored, and
explicitly specifying its data type. - Syntax
- Example
int myInteger
43Primitive 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
44Primitive 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
45Java 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
46Precedence 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
47Named Constants
- Magic Numbers
- A number in source code that means something to
the programmer, but looks like gibberish to other
readers. Example - The reader is left wondering what does the 28
represent? - Solution named constants!
if (i 28) System.out.println(Hello!)
48Named Constants
- We can declare a named constant using the keyword
final to make the code more readable - 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.
final int HELLO_MENU_OPTION 28 if (i
HELLO_MENU_OPTION) System.out.println(Hello!)
49Assignment Rules
- An integer value can be assigned to
- An integral variable type
- A floating point variable type
- A floating point value can only be assigned to a
floating-point variable type - However, we can cheat and change a values type
by typecasting it. For example - i will now store the value 5
int i 5
double i 5
double i 5.0
int i (int)5.4
50Computer Science 026a
Distilled
Module 4 Primitive Data Types - Boolean
51Conditional Execution
- Recall that our if statements have the
following form - 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.
if ( ) statement
52Comparison Operators
- Boolean expressions compare values using
relational operators
53Logical Operators
- Boolean expressions can be combined using the
logical operators - Although not explicitly required, good style
dictates that we should put parentheses around
each individual condition, as well as around the
entire compound condition.
54Logical Operators
- Truth table for the logical operators
55Logical Operator Precedence
- Java evaluates logic operators according to the
following precedence - Parentheses
- ! (Negation)
- (AND)
- (OR)
- Example
- A B !C
- evaluates as
- A (B !C)
56Primitive 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 - Shortcut when using boolean variables in
conditions, we can say - This is equivalent to
boolean isThisOverYet false
if (isThisOverYet)
if (isThisOverYet true)
57Nested If Statements
- if statements can be nested within other if
statements - Notice that we dont need braces in this case.
This is because an entire if-else block is
considered to be one statement.
if (age 16) if (hasLicense) System.out.pri
ntln(Turn on the car!) else System.out.pri
ntln(Sorry, go get a license!) else
System.out.println(Youre not even old enough!)
58The Evil Dangling Else
- Consider the following code
- Problem Do we associate the else with the outer
if statement, or the inner if statement? We call
this the dangling else problem.
if (age 16) if (hasLicense) System.out.pri
ntln(Turn on the car!) else
System.out.println(Youre not even old enough!)
59The 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 - Result Not what we wanted!
if (age 16) if (hasLicense) System.out.pri
ntln(Turn on the car!) else System.out.pri
ntln(Youre not even old enough!)
60The 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.p
rintln(Turn on the car!) else
System.out.println(Youre not even old enough!)
61Switch 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) else if (month 2)
. . .
switch (month) case 1 case
3 break case 2 break
62Switch 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!
63Switch 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
64Computer Science 026a
Distilled
Module 5 Iteration
65Control 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)
- dowhile (post-tested, non-deterministic)
66The for Loop
- Performed once before loop
begins - Checked before loop starts and after
the end of each iteration. Loop starts/continues
as long as it is true. - Performed at the end of each
iteration - Statement performed each iteration.
for ( )
67The for Loop
- Example Executing a statement 3 times.
- Lets examine the flow of execution
for (int i 0 i System.out.println(This is iteration i)
68The for Loop
Declare a variable i and set it to 0
for (int i 0 i System.out.println(This is iteration i)
Output
i 0
69The for Loop
Check is i less than 3?
for (int i 0 i System.out.println(This is iteration i)
Output
i 0
70The for Loop
Yep, lets execute the loop!
for (int i 0 i System.out.println(This is iteration i)
Output
i 0
71The for Loop
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0
i 0
72The for Loop
Increment i by 1
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0
i 1
73The for Loop
Check is i less than 3?
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0
i 1
74The for Loop
Yep, lets execute the loop!
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0
i 1
75The for Loop
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration 1
i 1
76The for Loop
Increment i by 1
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration 1
i 2
77The for Loop
Check is i less than 3?
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration 1
i 2
78The for Loop
Yep, lets execute the loop!
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration 1
i 2
79The for Loop
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration
1 This is iteration 2
i 2
80The for Loop
Increment i by 1
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
81The for Loop
Check is i less than 3?
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
82The for Loop
No sir, were moving on!
for (int i 0 i System.out.println(This is iteration i)
Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
83The while Loop
- Checked before loop starts and after
the end of each iteration. Loop starts/continues
as long as it is true. - 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.
while ()
84The while Loop
- Example Executing a statement 3 times.
- Lets examine the flow of execution
int i 0 while (i This is iteration i) i
85The while Loop
int i 0 while (i This is iteration i) i
Output
i 0
86The while Loop
Check Is i int i 0 while (i This is iteration i) i
Output
i 0
87The while Loop
Yep, lets execute the loop!
int i 0 while (i This is iteration i) i
Output
i 0
88The while Loop
int i 0 while (i This is iteration i) i
Output This is iteration 0
i 0
89The while Loop
int i 0 while (i This is iteration i) i
Output This is iteration 0
i 1
90The while Loop
Check Is i int i 0 while (i This is iteration i) i
Output This is iteration 0
i 1
91The while Loop
Yep, lets execute the loop!
int i 0 while (i This is iteration i) i
Output This is iteration 0
i 1
92The while Loop
int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration 1
i 1
93The while Loop
int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration 1
i 2
94The while Loop
Check Is i int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration 1
i 2
95The while Loop
Yep, lets execute the loop!
int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration 1
i 2
96The while Loop
int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration
1 This is iteration 2
i 2
97The while Loop
int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
98The while Loop
Check Is i int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
99The while Loop
No sir, were moving on!
int i 0 while (i This is iteration i) i
Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
100The dowhile Loop
- Checked after the loop has executed
once, and after each subsequent iteration. Loop
continues as long as it is true. - 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.
do while ( )
101The dowhile Loop
- Example Executing a statement 3 times.
- Lets examine the flow of execution
int i 0 do System.out.println(This is
iteration i) i while (i
102The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Output
i 0
103The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Output This is iteration 0
i 0
104The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Output This is iteration 0
i 1
105The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Check Is i Output This is iteration 0
i 1
106The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Yep, lets execute the loop!
Output This is iteration 0
i 1
107The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Output This is iteration 0 This is iteration 1
i 1
108The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Output This is iteration 0 This is iteration 1
i 2
109The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Check Is i Output This is iteration 0 This is iteration 1
i 2
110The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Yep, lets execute the loop!
Output This is iteration 0 This is iteration 1
i 2
111The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Output This is iteration 0 This is iteration
1 This is iteration 2
i 2
112The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
113The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i Check Is i Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
114The dowhile Loop
int i 0 do System.out.println(This is
iteration i) i while (i No sir, were moving on!
Output This is iteration 0 This is iteration
1 This is iteration 2
i 3
115Computer Science 026a
Distilled
Module 6 Modularity
116Benefits of Modularity
- By breaking up a problem into modules, we make it
easier to modify and maintain - Dont 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!
- Corollary More time spent sleeping!
117Modularity 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
118Modularity 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
119Modularity in Java
- Methods
- Contained within classes
- Implement the behaviour of a class that is, they
perform actions (like calculating how much longer
Im 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.
120Methods
- 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, were using the class name (Math) not the
name of a variable. - However, if were invoking (calling) static
methods that exist in the same class, we dont
need to specify the class name - Recall from assignment 3 searchForCompany(compan
y) - This is a static method, but since were calling
it from the same class, we dont need to say
TestPopcorn.searchForCompany
121Methods
- 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
- More on these methods a bit later
// 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)
122Defining a Static Method
- Syntax
- The type of the value returned by
the class. Some possible types - int, String, double, float
- void Class doesnt return anything
- An identifier associated with the
method that will be used to call it. - 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.
public static (
)
123Defining a Static Method
- Example
- 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?
public static double getAverage(int num1, int
num2, int num3) return (double)(num1 num2
num3) / 3
124Invoking a Static Method
- Example
- We invoke a static method by using its name
followed by parentheses. If the method takes
parameters, we put the values were passing into
the method in the parentheses. - Actual parameters The values were passing in
- Formal parameters The value types expected by
the method (the contract of the method)
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)
125Formal vs. Actual Parameters
- Formal parameters
- The contract of the method
- The method definition says, Hey! It you want to
call me, this is what youre 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)
126Formal vs. Actual Parameters
/ 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)
127Passing 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?
128Passing 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?
129Method 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
130Method 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)
131Method 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
- A methods prototype is also called its signature
public static int max(int num1, int num2) public
static double max (int num1, int num2) public
static float max(float num1, float num2)
132Computer Science 026a
Distilled
Module 7 Object-Oriented Design
133Object-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(), )
134Classes
- 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.
135Classes
- 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.
136Classes vs. Objects
- Consider a blueprint of a house.
- We cannot open the blueprints door, or close the
blueprints 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.
137Types 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 user-defined class.
138Defining a Class in Java
- For example, we might define a Person class
- We are then required to save this class in a file
named Person.java.
public class
public class Person
139Instance 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).
140Instance Variables
- Lets add name and age instance variables to our
Person class - 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.
public class Person private String name
private int age
141Instance Methods
- Instance methods are used to model the behaviour
of an object. - They are called on objects not on classes
- Person.setName(Jeff) // bad! Person is a
class - myPerson.setName(Jeff) // good! myPerson is
an object - They are declared exactly the same way as static
methods, except without the static keyword
public ( parameters )
142Instance Methods
- We classify instance methods as one of two types
- Accessor Methods
- Retrieve (access) data from the objects instance
variables - Do not change the objects state
- Examples
- getName()
- getAge()
- Mutator Methods
- Change (mutate) data in the object.
- Generally do not return anything.
- Examples
- setName(String newName)
- setAge(int newAge)
143Instance Methods
- Lets start by adding getName() and getAge()
accessor methods to our Person class - 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.
- No data is being changed it is simply returned
to the user.
public class Person private String name
private int age public String getName()
return name
public int getAge() return age //
end of class
144Instance Methods
- Now we need a way to change the objects state.
Well declare setName() and setAge() mutator
methods - 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.
public class Person private String name
private int age public void setName(String
name) this.name name
public void setAge(int age) this.age
age // accessor methods omitted //
end of class
145Instance 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 private String name
private int age public void setName(String
name) this.name name
public void setAge(int age) this.age
age // accessor methods omitted //
end of class
146Constructors
- 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 object
147Constructors
- A constructor that takes no parameters is called
the default constructor. It generally
initializes the object to some pre-defined 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
148Constructors
- The default constructor would be called if we
created a new Person object using the following
code - What would the following output?
- Answer The string NO NAME
- Why? Because our default constructor was coded
to initialize the Person objects name to NO
NAME.
Person p new Person()
Person p new Person() System.out.println(p.getN
ame())
149Constructors
- We usually overload constructors (specify
multiple constructors, each taking different
types and/or numbers of parameters). - Lets 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
150Constructors
- We can now create and initialize a new Person
object all in our line - What would the following output?
- Answer The string John
Person p new Person(John,12)
Person p new Person(John,12) System.out.print
ln(p.getName())
151Computer Science 026a
Distilled
Module 8 Equivalence
152Identity vs. State
- Lets 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.
153Identity vs. State
154Identity vs. State
155Identity vs. State
Crickets Chirping
Crickets Chirping
Crickets Chirping
Crickets Chirping
Crickets Chirping
156Identity vs. State
I have sandy blonde hair!
157Identity vs. State
Like, so do I!
158Identity vs. State
I have blue eyes!
159Identity vs. State
Whoa! Me too!
160Identity vs. State
We have state equality!
We have state equality!
161Identity vs. State
But Im not the same person as her!
162Identity vs. State
Ewww! No way!
163Identity vs. State
We dont have identity equality!
We dont have identity equality!
164Identity vs. State
- Thanks, ladies. Well 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(Theyre equal!)
165Identity 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.
166Identity vs. State
- Example of Identity Equality
- 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.
Person p new Person(John,12) Person q p
167Identity vs. State
- When dealing with reference types, the equality
operator () compares identity equality. - Line 3 will evaluate to true since they point to
the same object.
Person p new Person(John,12) Person q
p if (p q) System.out.println(Theyre
equal!)
168Identity vs. State
- If we want to check state equality, we need to
use the equals() method - Line 3 will evaluate to true since they have the
same state, even though they point to different
objects in memory.
Person p new Person(John,12) Person q new
Person(John,12) if (p.equals(q))
System.out.println(Theyre equal!)
169Computer Science 026a
Distilled
Module 9 Strings
170What is a String?
- A string is simply a sequence of characters a
combination of any of the following - Letters
- Numbers
- Symbols
- Spaces
- In Java, a string literal is enclosed in quotes
(but the quotes are not part of the string they
merely delimit it!) - Hello, World!
- When we use strings in Java, were actually using
objects of the String class (defined in the Java
API)
171Using 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 - We can declare String variables without using the
keyword new (we could technically create them
using the new keyword if we wanted to) - Despite these differences, String variables are
still reference variables that is, they point to
objects in memory
System.out.println(Hello, world!)
String myString Hello, world!
172Using Strings
- If we want to clear a String variable, we can
assign to it the empty string - We could check a Strings length using the
length() method - We could convert all letters in a String to
uppercase
String myStr
System.out.println( myStr.length() )
myStr myStr.toUpperCase()
173Changing 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