Lecture 17, CS 302-6, October 12
- Reminders
- Exam
1 – October 20, 5-7 pm
i.
Room: Chemistry 1351
- Program
2 – October 28, 10 pm
- Review
- Void
methods
- Stepwise
Refinement
- Example – LeapYear.java
- Variable
scope
- Definition
– the part of the program in which you can access it
- Based
on where you declare it (where you do: int a)
- The
scope is within the block you declare it in
i.
Local variable – variable that is defined within a method
ii.
As opposed to static variables – defined outside of
methods. We’ll get to this in a couple
of weeks
- Variables
scopes must not overlap
- Can
use the same name for variables as long as their 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.
- Examples:
This works:
For(int I=1;I<10;i++)
{
//Do
something
}
for(int I=1;I<10;I++)
{
//Do
something else
}
This does not work:
For(int I=1;I<10;I++
{
for(int
I=1;I<10;I++)
{
//Do something
}
}
- The
Call Stack and Call Stack Tracing
- What
actually happens when we call a method…
i.
Consider a main method that calls some method mystery
- Activation
record: stores information about the method, including all local
variables (including params).
Think of it as a box with all of the method data in it.
- So,
when we call ‘mystery’ from ‘main’, this is what happens:
i.
suspend main
ii.
do mystery
iii.
when mystery is completed, return to main
- 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. When we are done with
it, we return to the box below, and cross it out.
- Example
– CallStackTracing.pdf, CallStackTracing.java
- Call-execute-return
sequence
- This
is a step-by-step detail of what happens when we call a method
- Start
up called method
i.
allocate an activation record for the called method
ii.
allocate space in the new AR for param vars
iii.
copy param vals into corresponding param vars
1.
pass by value
- execute
method
- return
to caller
i.
remove called method’s AR (free up memory)
ii.
replace method call with its return value (if not void)
- continue
executing statements in the caller method
- Passing
arrays as parameters
- We’ve
already learned about how we can pass integers, doubles, Booleans, etc as
arguments (parameters) to methods.
- We
can also pass arrays of values as arguments
- Example
– Averages.java
- HW –
read and think about 6.5