Lecture 16, CS 302-7 and 8, February 27
- Review
- Methods
i.
As black box
1.
Methods should be designed to do one discrete thing
ii.
Declaring, Using
iii.
Parameters/arguments, return values
- Parameters,
arguments, return values
- Number
– 0 or 1 return, any number of args
- Type
– specify. Can be primitive or class type
- Bottles.java
- Fyi: http://99-bottles-of-beer.net/
- Void
methods
- Declare
method as ‘void’ (instead of return type)
i.
For instance, main method
ii.
Other examples – methods that just print things, etc
- End
with return; or just with }
i.
Neither is really better/preferred – you’ll see both
- Can
still have return; in the middle to exit early
- Using
void methods: method(); (as opposed to something=method();)
- Example
– Drawer.java
- Technical
details of parameters
- Parameter
‘variable’ and parameter ‘value’
i.
Parameter variable in method declaration
ii.
Parameter value when you call the method
- Pass
by value, not reference
i.
Changing a value in a method does not change the value in the
method that called it
- Variable
names in separate blocks are separate
- CallStack.java
- More
on return statements
- Can
return literals, variables, expressions, etc…
- Immediately
exits the method call
- You
can use return; at different points in a method call
i.
Example – safe divide method.
Return early if /0. Else perform
divide
- Watch
out for – unreachable code, branches without returns
- Watch
out for – make sure to STORE return value, not just compute it.
- HW
- Read
5.6-5.7