# PowerPoint Presentation

Document Sample

```					Lec.4
Methods: Functional Abstraction

Jiang (Jen) ZHENG
May 18th, 2005
Outline
 Quick Review
 Implementation Detail
 Remote Access
 Submission

 Method Concepts
 Method invocation
 Static method
 Call by value
 Scope of variables
 Method Recursion
CS401/COE401 Summer 2005.Department of   2
Computer Science.University of
Pittsburgh.Lecture 4
Quick Review:
Statements and Block
 Variable declaration statements Ex: double size=1.5, x;
 Expression statements
   Assignment expression Ex: area= width*height;
   Method call expression Ex: System.out.println(…);
 Empty Statement: ; (no action)
 Conditional Statement: if-else, switch
 Iterative Statement: for, while
 Other statements: break, continue
 Block: a grouping of a number of statements enclosed by
braces. Can be nested blocks.

CS401/COE401 Summer 2005.Department of   3
Computer Science.University of
Pittsburgh.Lecture 4
Quick Review: Boolean Algebra
 Relational and equality operators
   <, >, ==, <=, >=, !=
 Logical Operators
   &&, ||, !
 Operator Precedence and Associativity
Operator                                                         Associativity
()   ++(postfix) --(postfix)                                     Left to right
+(unary) -(unary) ++(prefix) --(prefix) !                        Right to left
new (type)expr                                                   Right to left
* / %                                                            Left to right
+ -                                                              Left to right
<        <=         >          >=                                Left to right
==       !=                                                      Left to right
&&                                                               Left to right
||                      CS401/COE401 Summer 2005.Department of   Left to right   4
= += -= *= /= %= Computer Science.University of
etc.
Pittsburgh.Lecture 4
Right to left
 How to use Package?
 import tio.*;
 Compile the java files of the tio package
 The hierarchical of your program and the tio package
 Fibonacci Numbers:
 F(0) = 1, F(1) = 1, F(2) = F(1)+F(0) = 2,
 F(3) = F(2) + F(1) = 2 + 1 = 3
 F(4) = F(3) + F(2) = 3 + 2 = 5
 F(5) = F(4) + F(3) = 5 + 3 = 8
 F(6) = F(5) + F(4) = 8 + 5 = 13
 F(7) = F(6) + F(5) = 13 + 8 = 21 …
   Implementation:
   use two parameters to represent the previous two F values of the current number
   Update the two F values as the current number is going forward
   Special situation:
 F(0) = F(1) =1

CS401/COE401 Summer 2005.Department of                    5
Computer Science.University of
Pittsburgh.Lecture 4
Account
 Using telnet from your dos window.
   telnet unixs.cis.pitt.edu
 Using F-Secure SSH Client software
(Recommend)
 Or compile and run from your home PC
 Demo the first two

CS401/COE401 Summer 2005.Department of   6
Computer Science.University of
Pittsburgh.Lecture 4
Submission
 You should be able to submit your assignment now.
 The submission directory is:
/afs/cs.pitt.edu/public/incoming/CS401/zheng/yourname/
 Submission Command:
   cp [filename] [submission directory]
   For example:
cp Fibonacci.java /afs/cs.pitt.edu/public/incoming/CS401/zheng/SStachelski/lab2

CS401/COE401 Summer 2005.Department of                    7
Computer Science.University of
Pittsburgh.Lecture 4
 Evaluate the init_expr expression
 Entering Point:
 the case label having a constant value that matches
the value of the expression found in step 1;
 the default label if there is no match;
 terminate switch if there is no default label, .
 Continue executing statements in order
 Exiting Point:
 the end of switch
 a break is encountered.
 Demo ex4.java

CS401/COE401 Summer 2005.Department of   8
Computer Science.University of
Pittsburgh.Lecture 4
Methods and Method Calls
 If programs are short
 We can write the code as one contiguous segment
 The logic is probably simple

 There are not too many variables

 Not too likely to make a lot of errors

 As programs get longer
 Programming in a single segment gets more and
more difficult
 Logic is more complex

 Many variables / expressions / control statements

CS401/COE401 Summer 2005.Department of   9
Computer Science.University of
Pittsburgh.Lecture 4
Methods and Method Calls
   Chances of “bugs” entering code is higher
 Isolating and fixing is also harder
   If multiple people are working on the program, it is
difficult to “break up” if written as one segment
   If parts need to be modified or added, it is difficult with
one large segment
   If similar actions are taken in various parts of the
program, it is inefficient to code them all separately
 And can also introduce errors
   Most of these problems can be solved by breaking our
program into smaller segments
 Ex: Break some sticks!

CS401/COE401 Summer 2005.Department of      10
Computer Science.University of
Pittsburgh.Lecture 4
Method Invocation
 Method (or function or subprogram)
   A segment of code that is logically separate
from the rest of the program
   When invoked (i.e. called) control jumps from
main to the method and it executes
   Usually with parameters (arguments)
   When it is finished, control reverts to the next
statement after the method call

CS401/COE401 Summer 2005.Department of   11
Computer Science.University of
Pittsburgh.Lecture 4
Method Invocation
 When a method is called or invoked
   the program control passes to the method
   the method does its work
   the program control is passed back

Program Control

Program Control
Method Call

Program Control

CS401/COE401 Summer 2005.Department of   12
Computer Science.University of
Pittsburgh.Lecture 4
Functional Abstraction
 Methods provide us with functional (or procedural)
abstraction
   We do not need to know all of the implementation
details of the methods in order to use them
 We simply need to know

 What arguments (parameters) we must provide
 What the effect of the method is (i.e. what does it do?)
   The actual implementation could be done in several
different ways
   Ex: Predefined method: sort(Object [] a)
 There are many ways to sort!

CS401/COE401 Summer 2005.Department of            13
Computer Science.University of
Pittsburgh.Lecture 4
Predefined Methods
 There are MANY predefined methods in Java
   Look in the online API
   These are often called in the following way:
ClassName.methodName(param_list)
 Where ClassName is the class in which the method is

defined
 Where methodName is the name of the method

 Where param_list is a list of 0 or more variables or

expressions that are passed to the method
Ex: Y = Math.sqrt(X);
 These are called STATIC methods or CLASS methods

 They are associated with a class, not with an object

CS401/COE401 Summer 2005.Department of      14
Computer Science.University of
Pittsburgh.Lecture 4
Predefined Methods
   Some are also called in the following way
ClassName.ObjectName.methodName(param_list)
• Where ObjectName is the name of a static, predefined
object that contains the method
Ex: System.out.println(“Hello There”);
 System is a predefined class

 out is a predefined PrintStream object within System

 println is a method within PrintStream

   We’ll use these now, but discuss their nature more
when we discuss object-oriented program.
   For now we will concentrate on static methods

CS401/COE401 Summer 2005.Department of   15
Computer Science.University of
Pittsburgh.Lecture 4
Static Method In One Page
 static method / class method / predefined method
 General Form:
 public static ReturnType Identifier (ParameterList) block
 For Ex:
public static double square ( double x) {
double result; // Variable Declaration
result = x*x; // statements
return result; // return statement: can return a value or return a
// value of an expression. Ex: return x*x;
}
 Return Type
 the type of the value returned
 Or void if nothing returned.
 Parameter List
0 or more parameters passed to the method
 Each parameter: type identifier
 Place holder for actual values.
 public keyword is optional. Exception: main()

CS401/COE401 Summer 2005.Department of               16
Computer Science.University of
Pittsburgh.Lecture 4
Return Value vs. Void
 Java methods have two primary uses:
 To act as a function, returning a result to the calling code
 In Java these methods are declared with return types, and

are called within an assignment or expression
Y = (Math.sqrt(X))/2;
   To act as a subroutine or procedure, executing code but not
explicitly returning a result
 In Java these methods are declared to be void, and are

called as separate stand-alone statements
Ex:   System.out.println(“Wacky”);
Arrays.sort(myData);

CS401/COE401 Summer 2005.Department of   17
Computer Science.University of
Pittsburgh.Lecture 4
Writing Static Methods
 What if we need to use a method that is not predefined?
 We will have to write it ourselves
 Syntax:
public static void methodName(param_list)
{ // method body
}
public static retval methodName(param_list)
{ // method body
}
   Where retval is some Java type
   When method is not void, there MUST be a return statement

CS401/COE401 Summer 2005.Department of   18
Computer Science.University of
Pittsburgh.Lecture 4
Writing Static Methods
   So what about the param_list?
 It is a way in which we pass values into our methods

 This enables methods to process different information

at different points in the program
 Makes them more flexible
   In the method definition:
 List of    type identifier                        pairs,
separated by commas
 Called formal parameters, or parameters
   In the method call:
 List of variables or expressions that match 1-1 with the
parameters in the definition
 Called actual parameters, or arguments
CS401/COE401 Summer 2005.Department of            19
Computer Science.University of
Pittsburgh.Lecture 4
Writing Static Methods
Ex:
{
return ans;                            parameter
}                                          argument
…

   Note: If method is called in same class in which it was
defined, we don’t need to use the class name in the call

CS401/COE401 Summer 2005.Department of     20
Computer Science.University of
Pittsburgh.Lecture 4
Parameters
   Parameters in Java are passed by value
 The parameter is a copy of the evaluation of the

argument
 Any changes to the parameter do not affect the

method completed
Main Class                                                     area method
value passed from

theArea    12.566…
result returned to                       ans     12.566…
main
double ans = Math.PI
main calls area
CS401/COE401 Summer 2005.Department of                          21
Computer Science.University of
Pittsburgh.Lecture 4
More on Parameters
 Effect of value parameters:
 Arguments passed into a method cannot be changed
within the method, either intentionally or accidentally
 Good result: Prevents accidental side-effects from

methods
 Bad result: What if we want the arguments to be

changed?
 Ex: swap(A, B)
 Method swaps the values in A and B
 But with value parameters will be a “no-op”
 We can get around this issue when we get into object-
oriented programming

CS401/COE401 Summer 2005.Department of         22
Computer Science.University of
Pittsburgh.Lecture 4
Local variables and scope
 Variables declared within a method are local to that
method
   They exist only within the context of the method
   This includes parameters as well
 Think of a parameter as a local variable that is

initialized in the method call
   We say the scope of these variables is point in the
method that they are declared up to the end of the
method

CS401/COE401 Summer 2005.Department of   23
Computer Science.University of
Pittsburgh.Lecture 4
Local variables and scope

 However, Java variables can also be
declared within blocks inside of methods
   In this case the scope is the point of the
declaration until the end of that block
   Be careful that you declare your variables in
the correct block
 Demo on board

CS401/COE401 Summer 2005.Department of   24
Computer Science.University of
Pittsburgh.Lecture 4
Local variables and scope
 Note that either way, these variables cannot
be shared across methods
   We can still get data from one method to
another
   How?           Return Statement

 To share variables across methods, we need
to use object-oriented programming
   We will see this soon!

CS401/COE401 Summer 2005.Department of   25
Computer Science.University of
Pittsburgh.Lecture 4
Recursion
 A Java method can call any other public Java method
 main() is just a method itself, and we have called other
methods from it
 Thus, a method should be able to call itself – we call
this a RECURSIVE CALL
 Since it is a method

 At first thought this seems odd or even impossible –
why would we want to do this?
 However, it will be very useful in a lot of different

programming approaches

CS401/COE401 Summer 2005.Department of   26
Computer Science.University of
Pittsburgh.Lecture 4
Recursion
   Before we look at the programming in detail, let’s try to get
the idea down, using math
   Some mathematical functions are in fact defined recursively
 Example in text: Factorial

N! = N * (N-1)!
 Note that the function is defined in terms of itself, but with an

important change:
 The “recursive call” is smaller in size (N-1) than the original call (N)
 This is vital to recursion being viable
   Let’s trace 4! in this way to see what happens (see board)
 Uh oh!

CS401/COE401 Summer 2005.Department of              27
Computer Science.University of
Pittsburgh.Lecture 4
Recursion
   What we are missing in the previous slide is a
condition that allows the recursion to stop
   Every recursive algorithm must have some
terminating condition, to keep it from recursing
“forever”
   We call this the BASE CASE
   What is the base case for factorial? 0! = 1
N! = N * (N-1)!              when N > 0
N! = 1                       when N = 0
   This now allows us to complete our algorithm:
CS401/COE401 Summer 2005.Department of   28
Computer Science.University of
Pittsburgh.Lecture 4
Recursion
   Three important rules for any recursive
algorithm:
1)   There must be some recursive case, in which
the algorithm “calls itself”
2)   There must be some base case, in which no
3)   The recursive calls must lead eventually to the
base case
   Usually by “reducing” the problem size in some way
   Don’t forget these!

CS401/COE401 Summer 2005.Department of     29
Computer Science.University of
Pittsburgh.Lecture 4
More Recursion
   Let’s look at another example:
   Calculating an integer power of another integer
MN = M * MN-1               N>0               recursive case
   Don’t forget the base case
MN = 1                     N=0               base case
   The actions we take are slightly different from
factorial, but the basic idea is similar
   Trace this on board
   Note how first call made is last call to complete
   This is important in the implementation of
recursion
CS401/COE401 Summer 2005.Department of      30
Computer Science.University of
Pittsburgh.Lecture 4
Implementing Recursion
 So how do we implement recursion?
 Luckily the computer code is very similar to the
mathematical functions
 Consider factorial below
 Note that the recursive call is made within the return

statement
 This is fine – return is done AFTER call completes
public static int fact(int N)
{
if (N <= 1)
return 1;
else
return (N * fact(N-1));
}

CS401/COE401 Summer 2005.Department of   31
Computer Science.University of
Pittsburgh.Lecture 4
Implementing Recursion
 How does recursion actually work?
 Each time a method is called, an activation record (AR)
is allocated for it
 This consists of memory for the parameters and local

variables used in the method
 Each new activation record is placed on the top of the
run-time stack
 When a method terminates, its activation record is
removed from the top of the run-time stack
 Thus, the first AR placed onto the stack is the last one
removed

CS401/COE401 Summer 2005.Department of   32
Computer Science.University of
Pittsburgh.Lecture 4
Implementing Recursion
N = 1
N <= 1? YES                                                 fact(1)
return                              1

N = 2
N <= 1? NO         1                                        fact(2)
return (2 * fact(1)) =              2

N = 3
N <= 1? NO         2
fact(3)
return (3 * fact(2)) =              6

N = 4
N <= 1? NO         6
fact(4)
return (4 * fact(3)) =             24

24
CS401/COE401 Summer 2005.Department of             33
Computer Science.University of
Pittsburgh.Lecture 4
Recursion
 Think about the Lab 2 using recursive function?
 Recursive Case:
 F (n) = F(n-1) + F(n-2)
 Base Case:
 F(1) = F(0) = 1
 The Recursive case will lead to base case
 Final Code:
   public static int Fibonacci ( int index) {
if ( index == 0 || Index == 1)
return 1;
else return Fibonacci (index -1) + Fibonacci (index -2);
}
CS401/COE401 Summer 2005.Department of        34
Computer Science.University of
Pittsburgh.Lecture 4
Recursion vs. Iteration
   Some recursive algorithms can also be easily
implemented with loops
   Both factorial and power can easily be done in
this way
   When possible, it is usually better to use iteration,
since we don’t have the overhead of the run-time
stack (that we just saw on the previous slide)
   Other recursive algorithms are very difficult to
do any other way
   You will see more about recursion in CS 0445
   For now, let’s look at ex6.java
CS401/COE401 Summer 2005.Department of   35
Computer Science.University of
Pittsburgh.Lecture 4
Topics for next lecture
You don’t need to know the details but you should
know what are those when I talk about it.

CS401/COE401 Summer 2005.Department of   36
Computer Science.University of
Pittsburgh.Lecture 4

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 0 posted: 2/8/2013 language: English pages: 36
How are you planning on using Docstoc?