Lecture 17, CS 302-7 and 8, February 29
- Reminders
- Exam
1 – March 8
- Program
2 – Coming soon
- Review
- The
call stack
- Void
methods
- Stepwise
Refinement
- Think
of your program as a sort of flowchart – you want to think of each
possible case, and what happens after it
- http://xkcd.com/627/
i.
Squares and diamonds can be thought of as methods, not just
statements and conditions
- The
idea is to break a complicated problem down into manageable cases, and
solve those
- Think
of these small cases as methods/black boxes – abstract out the details.
- Example
– LeapDay.java
i.
Via stepwise refinement – think about each possible case
- Variable
scope
- Definition
– the part of the program in which you can access it
- Based
on where you declare it (int a)
- Within
the block you declare it in
i.
Local variable – variable that is defined within a method
ii.
As opposed to static variables – outside of methods. Later…
- Scopes
must not overlap
i.
Think of your program as a tree of blocks…
- Can
use same name as long as scope doesn’t overlap
- Example
that doesn’t work: int I in a for loop within a method that already has
defined int I
- But,
int I within separate for loops works.
- The
call stack
- What
actually happens when we call a method…
i.
main method that calls mystery
ii.
Vocab: Caller and callee
- Definition:
Activation record. This stores
information about the method, including all local variables (including
params). Think of it as a box.
- So…when
we call a method…suspend main, do mystery, when mystery is completed,
return to main
i.
Generally: suspend caller, do callee, return to caller
- Think
of mystery as another box [AR] that we put on top of main. We only do the top most box at any
given time, and then we drop one etc.
- More
technical details:
- Call-execute-return
sequence
i.
Start up called method
1.
allocate an activation record for the called method
2.
allocate space in the new AR for param vars
3.
copy param vals into corresponding param vars
a.
pass by value
ii.
execute method
iii.
return to caller
1.
remove called method’s AR (free up memory)
2.
replace method call with its return value (if not void)
iv.
continue in caller…
- Passing
arrays
- General
point – we can do it J
i.
Example – Averages.java
- HW –
read and think about 6.5