Lecture 15 - Methods
Lecture 15 - Methods
Introduction to programming
Lecture 15 Methods
LECTURE OBJECTIVES
(JFE, Chapter 5)
1. Methods as Black Boxes
• A method is a sequence of instructions with a name
• You declare a method by defining a named block of
code
public static void main(String[] args)
{
int z = Math.max(2, 3);
. . .
}
4
3. Flowchart of Calling a Method
callee
caller
8
7. Inside the Box
9
Back from the Box
11
Cubes.java: complete program
9. Method comments
16
Parameter Passing Steps
public static void main(String[] args)
{
double result1 = cubeVolume(2);
. . .
}
26
• The return statement terminates a method call and
yields the method result.
• Turn computations that can be reused into
methods.
• Use a return type of void to indicate that a method
does not return a value.
• Use the process of stepwise refinement to
decompose complex tasks into simpler ones.
27
19. Variable Scope
Scope of a variable:
This is part of a program in which a variable is visible.
• Variables can be declared:
a) Inside a method
• Known as ‘local variables’
• Only available inside this method
• Parameter variables are like local variables
b) Inside a block of code { }
• Sometimes called ‘block scope’
• Declared inside block { ends at end of block }
c) Outside of a method
• Sometimes called ‘global scope’
• Can be used (and changed) by code in any method
28
• How do you choose?
Examples of Scope
35
Computing Skills 36