0% found this document useful (0 votes)
8 views

Lecture 15 - Methods

Uploaded by

Lucia Motlhagodi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 15 - Methods

Uploaded by

Lucia Motlhagodi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

ISS112

Introduction to programming

Lecture 15 Methods
LECTURE OBJECTIVES

• By the end of this lecture you must be able to:


• implement methods
• understand parameter passing
• determine the scope of a variable

(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);
. . .
}

• A method is called in order to execute its instructions


A method packages computation consisting
of multiple steps into a form that can be easily
understood and reused. 3
2. What is a method?

• Some methods you have already used are:


• Math.max()
• nextInt() (Scanner class)
• length() (String class)
• printf()
• main()
• They all have:
• A name: Follow the same rules as variable names
• ( ) at the end : A place to receive input information

4
3. Flowchart of Calling a Method

public static void main(String[] args)


{
double z = Math.pow(2, 3);
. . .
}

• One method ‘calls’ another


• main calls Math.pow()
• Passes two variables : 2 & 3
• Math.pow starts
• Uses variables (2, 3)
• Does its job
• Returns the answer
• main uses result 5
4. Parameters and Return Values
public static void main(String[] args)
{
double z = Math.pow(2, 3);
. . .
}

callee
caller

• main ‘passes’ two parameters to Math.pow


• Math.pow calculates and returns a value of 8 to main
• main stores the return value in variable z 6
5. Black Box Analogy

• A thermostat is a ‘black box’


• Set a desired temperature
• Turns on heater/AC as required
• You don’t have to know how it really works!
• How does it know the current temp?
• What signals/commands does it send to the
heater or A/C?
• Use methods like ‘black boxes’
– Pass the method what it needs to do its job
– Receive the answer
7
6. Implementing Methods

• A method to calculate the volume of a cube


• What does it need to do its job?
• What does it answer with?

• When writing this method:


• Pick a name for the method (cubeVolume).
• Give a type and a name for each parameter
variable (double length)
• Specify the type of the return value ( double )
• Add modifiers such as public static

public static double cubeVolume(double length)

8
7. Inside the Box

• Then write the body of the method


• The body is surrounded by curly braces { }
• The body contains the variable declarations and
statements that are executed when the method is
called or invoked
• It will also return the calculated answer

public static double cubeVolume(double length)


{
double volume = length * length * length;
return volume;
}

9
Back from the Box

• The values returned from cubeVolume are stored in local


variables inside main
• results1 and results2 in this case
• The results are then printed out

public static void main(String[] args)


{
double result1 = cubeVolume(2);
double result2 = cubeVolume(10);
System.out.printf(“A cube of length 2 has volume %f”,
result1);
System.out.printf(“A cube of length 10 has volume %f”,
result2);
}
10
8. Method Declaration

11
Cubes.java: complete program
9. Method comments

• Start with /** (Javadoc multiline comment)


• Note the purpose of the method
• Describe each parameter
• Describe the return value
• End with */
/**
Computes the volume of a cube.
@param sideLength the side length of the cube
@return the volume
*/
public static double cubeVolume(double sideLength)
{
. . .
} 13
10. Repeated code into a method

• Find Repetitive Code


• May have different values but same logic
int hours;
System.out.print("Enter a value between 1 and 12: ");
hours = in.nextInt();
while (hours < 1 || hours > 12) {
1 - 12 System.out.print("Enter a value between 1 and 12: ");
hours = in.nextInt();
}
//
int minutes;
System.out.print("Enter a value between 0 and 59: ");
minutes = in.nextInt();
0 - 59 while (minutes < 0 || minutes > 59) {
System.out.print("Enter a value between 0 and 59: ");
minutes = in.nextInt();
} 14
11. Write a ‘Parameterized’ Method
/**
Prompts a user to enter a value in a given range
until the user provides a valid input.
@param low the low end of the range
@param high the high end of the range
@return the value provided by the user
*/

public static int readValueBetween(int low, int high)


{
int input;
while (input < low || input > high) {
System.out.printf("Enter value between %d and %d:
" ,low , high);
Scanner in = new Scanner(System.in);
input = in.nextInt();
}
8 return input;
} 15
12. Parameter Passing
• Parameter variables hold the parameter values supplied in
the method call:
• Both must be of the same data type Calling
• The parameter value may be: Method
• The contents of a variable o
Parameter value u
• A ‘literal’ value (2)
t
• aka. ‘actual parameter’ or argument
• The parameter variable is:
Parameter variable
in
• Named in the called method declaration Called
• Used as a variable inside the called method Method
• aka. ‘formal parameter’

16
Parameter Passing Steps
public static void main(String[] args)
{
double result1 = cubeVolume(2);

. . .
}

public static double cubeVolume(double sideLength)


{
double volume = sideLength * sideLength * sideLength;
return volume;
17
}
Common Error 1

• Trying to Modify Parameters


• A copy of the parameter value is passed
• Called method (addTax) can modify local copy (price)
• But not original public static void main(String[] args)
{
in calling method double t, total = 10;
total
t = addTax(total, 7.5); 10.0
// print total here!
copy
}

public static double addTax( double price, double rate)


{
double tax = price * rate / 100;
price = price + tax; // Has no effect outside the method
return tax; price
} 18
10.75
13. Methods with Return Values
• Methods can (optionally) return one value
• The return type is specified in the method declaration
• The return statement does two things:
1) The method terminates immediately
2) The return value is returned to the calling method
Return type
public static double addTax(double price, double rate)
{
price += price * rate / 100;
return price;
}
Return value
 Return value: May be a value, a variable or a calculation
 Type must match return type 19
14. Multiple return Statements

• A method can use multiple return statements


• But Every branch must have a return statement

public static double cubeVolume(double sideLength)


{
if (sideLength < 0)
{
return 0;
}
return sideLength * sideLength * sideLength;
}
Common Error 2

• Missing Return Statement


• Make sure all conditions are handled
• In this case, x could be equal to 0
• No return statement for this condition
• The compiler will complain if any branch has
no return statement

public static int sign(double x)


{
if (x < 0) { return -1; }
if (x > 0) { return 1; }
// Error: missing return value if x equals 0
}
21
15. Steps to implement a Method
1) Describe what the method should do
2) Determine the method’s inputs
3) Determine the types of inputs and the return value
4) Write pseudocode for the desired result
5) Implement the method body

public static double pyramidVolume( double height,


double baseLength)
{
double baseArea = baseLength * baseLength;
return height * baseArea / 3;
}

6) Test the method


• Design test cases and code
16. Methods without Return Values

• Methods are not required to return a value


• The return type of void means nothing is returned
• No return statement is required
• The method can generate output though!
... public static void boxString(String str)
boxString(“Hello”); {
... int n = str.length();
for (int i = 0; i < n + 2; i++)
{ System.out.print("-"); }
System.out.println();
System.out.println("!" + str + "!");
for (int i = 0; i < n + 2; i++)
{ System.out.print("-"); }
System.out.println();
} 23
17. Using return Without a Value
• You can use the return statement without a value
• In methods with void return type
• The method will terminate immediately!
public static void boxString(String str)
{
int n = str.length();
if (n == 0)
{
return; // Return immediately
}
for (int i = 0; i < n + 2; i++) { System.out.print("-"); }
System.out.println();
System.out.println("!" + str + "!");
for (int i = 0; i < n + 2; i++) { System.out.print("-"); }
System.out.println();
} 24
Programming Tips

• Keep methods short


• Generally one screen
• Break into ‘sub’ methods if code is too long
• Trace your methods
• Use Stubs as you write larger programs
• Unfinished methods that return a ‘dummy’ value

public static String digitName(int digit)


{
return "mumble";
}
18. Summary: Methods

• A method is a named sequence of instructions.


• Parameter values are supplied when a method is called.
The return value is the result that the method computes.
• When declaring a method, you provide a name for the
method, a name and type for each parameter, and a type
for the result.
• Method comments explain the purpose of the method,
the meaning of the parameters and return value, as well
as any special requirements.
• Parameter variables hold the parameter values supplied
in the method call.

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

public static void main(String[] args)


{
int sum = 0;
for (int i = 1; i <= 10; i++) sum
{ i
int square = i * i;
sum = sum + square; square
}
System.out.println(sum);
}

• sum is a local variable in main


• i is only visible inside the for loop
• square is only visible inside the for loop block
29
Local Variables of Methods

public static void main(String[] args)


{
double sideLength = 10;
int result = cubeVolume();
System.out.println(result);
}
public static double cubeVolume()
{
return sideLength * sideLength * sideLength; // ERROR !
}
• Variables declared inside one method are not visible to other
methods
• sideLength is local to main
• It is unknown in cubeVolume in this case
30
• This will cause a compiler error
Re-using names for local variables

public static int square(int n)


{
int result = n * n;
return result; result
}

public static void main(String[] args)


{
int result = square(3) + square(4);
result
System.out.println(result);
}

• Variables declared inside one method are not visible to


other methods
• result is local to square and result is local to main
• They are two different variables and do not overlap 31
Re-using names for block variables
public static void main(String[] args)
{
int sum = 0; i
for (int i = 1; i <= 10; i++)
{
sum = sum + i;
} i
for (int i = 1; i <= 10; i++)
{
sum = sum + i * i;
}
System.out.println(sum);
}
• Variables declared inside one block are not visible to other blocks
• i is inside the first for block and i is inside the second
• They are two different variables and do not overlap
32
Overlapping Scope

public static int sumOfSquares(int n)


{
int sum = 0;
for (int i = 1; i <= n; i++) Local n
{
int n = i * i; // ERROR block scope n
sum = sum + n;
}
return sum;
}

• Variables (including parameter variables) must have


unique names within their scope
• n has local scope and n is in a block inside that scope
• The compiler will complain when the block scope n is
declared 33
Global and Local Overlapping
public class Scoper
{
public static int same; // ‘global’
public static void main(String[] args)
{ same
int same = 0; // local
for (int i = 1; i <= 10; i++)
Variables in
{ same different scopes
int square = i * i;
with the same name
same = same + square;
will compile, but
}
it is not a good idea
System.out.println(same);
}
}
• Global and Local (method) variables can overlap
• The local same will be used when it is in scope
• No access to global same when local same is in scope 34
20. Summary: Scope

• Local variables declared inside one method are not visible to


code inside other methods
• The scope of a variable is the part of the program in which it
is visible.
• Two local or parameter variables can have the same name,
provided that their scopes do not overlap.
• You can use the same variable name within different
methods since their scope does not overlap.

35
Computing Skills 36

You might also like