2. Copyright Warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been copied and communicated to you by or
on behalf of Bond University pursuant to Part VB of the
Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
under the Act. Any further copying or communication of this
material by you may be the subject of copyright protection
under the Act.
Do not remove this notice.
Š 2004 Pearson Addison-Wesley. All rights reserved 5-2
3. Software Construction
⢠As programs become larger, they become more
complicated
ď§ more variables, more loops, more nested structures
⢠We need ways to isolate this complexity
⢠All computer languages provide mechanisms to do
this, e.g.
ď§ methods, classes, packages, libraries, whole programs
⢠This week, we are going to look at methods
Š 2004 Pearson Addison-Wesley. All rights reserved 5-3
4. Methods
⢠A method is a âmini-programâ, with its own
variables and lines of code
⢠It usually get input by means of variables which
are passed to it
⢠The method can return one value, which is the
result of the âmini-programâ
⢠From the caller's point of view, the method is a
black box which performs some work, e.g
answer= generator.nextInt(MAX);
Š 2004 Pearson Addison-Wesley. All rights reserved 5-4
5. Some You Have Seen Already
⢠You have already used methods. Some take input
but provide no outputs, e.g
ď§ System.out.print(âhelloâ);
ď§ System.out.println(âhelloâ);
⢠Some methods take no input but return a value,
e.g.
ď§ guess= scan.nextInt();
ď§ name= scan.nextLine();
⢠Some take no inputs, and return nothing, e.g
ď§ public static void main();
⢠Taking input is optional, and so is returning a
value.
⢠It's up to the designer of the method to decide
what is required to make the method work
Š 2004 Pearson Addison-Wesley. All rights reserved 5-5
6. Why Methods?
⢠Methods help to isolate complexity: code to do a
certain task is contained within a method
⢠Methods allow you to think in terms of
âcomponentsâ:
ď§ get user input, print out a header, determine if a number
is valid
ď§ once you have written a method and tested that it is
correct, you can use it as a black box component
⢠Methods enforce the DRY Principle: don't repeat
yourself.
ď§ If you write the same code twice, bad. Why?
ď§ Convert it into a method, then call the method multiple
times
⢠Methods can be tested. This helps to prove that
your components work correctly
Š 2004 Pearson Addison-Wesley. All rights reserved 5-6
7. Your First Method
⢠Let's write a method to find the biggest of two
numbers.
⢠What inputs does it require?
ď§ two integers
⢠Does it need to return a value?
ď§ Yes, the value of the biggest number
⢠OK, let's call the two integers a and b
⢠We can write some of the Java code now:
if (a>b)
// then a is bigger, return its value
else
// b is bigger, return it instead
Š 2004 Pearson Addison-Wesley. All rights reserved 5-7
8. The return keyword
⢠The return keyword is used to return a value out of
a method. We can modify our code:
if (a>b)
return(a);
else
return(b);
⢠Note: the return ends the execution of the method.
If we return(a), then the code from else
onwards will not get executed
⢠All return()s in a method must return the same
type of data. Here, we always return an int
Š 2004 Pearson Addison-Wesley. All rights reserved 5-8
9. Declaring the Method
⢠We must now declare the method. This tells the
other Java code how to use the method and what it
will return
ď§ The method's name is maxOf
ď§ It takes two integers as input
ď§ It returns a single int value
public static int maxOf(int a, int b)
{
if (a>b)
return(a);
else
return(b);
}
Š 2004 Pearson Addison-Wesley. All rights reserved 5-9
10. Trying It Out With Bluej
⢠Let's try the code out in Bluej
ď§ Open a new program, note that it already comes with a
method called main()
ď§ Add the maxOf() code after the code for main()
ď§ Compile the program
⢠Now right-click on the file. You will see
⢠2004 Pearson Addison-Wesley.maxOf() method
Š
Select the All rights reserved 5-10
11. Trying It Out With Bluej
⢠Bluej will provide you with a window to enter the
input values to the method
⢠Enter two values and click OK
⢠Bluej runs the method, and shows you the result
returned by the method
Š 2004 Pearson Addison-Wesley. All rights reserved 5-11
12. Calling a Method
⢠Now it's time to call the method with real Java
code. Modify the main() method to have this
code:
int num1, num2, result;
num1= 76; num2= 3004;
result= maxOf(num1, num2);
System.out.println(âThe result isâ +
num1);
System.out.println( maxOf(2, 17-8) );
⢠Try to guess what will get printed out when the
main() method is run
Š 2004 Pearson Addison-Wesley. All rights reserved 5-12
13. Terminology
⢠The list of variables that are the inputs to a method
are known as its formal parameters
ď§ int maxOf(int a, int b)
a & b are formal parameters
⢠The values that are used when a method is called
are its actual parameters, or its arguments
result= maxOf(2, 17-9);
2 and 17-9 are the arguments
⢠The values of the arguments are calculated, and
copies of these values are assigned into the formal
parameters when the method is called
Š 2004 Pearson Addison-Wesley. All rights reserved 5-13
14. Call by Value
⢠Copying the values of the arguments into a
method is known as call by value
result= maxOf(2, 17-9);
maxOf(int a, int b)
return(...);
⢠Similarly, the value returned by the method is
copied back out the the caller of the method
⢠The formal parameters, and any variables declared
in the method are local variables
⢠They are not visible outside the method
Š 2004 Pearson Addison-Wesley. All rights reserved 5-14
15. Methods are Expressions
⢠Methods return a value. Therefore, they can be
treated as expressions
⢠You do not have to assign the result of a method
call, e.g in main():
int num1, num2;
System.out.print(âEnter a num: â);
num1= scan.nextInt();
System.out.print(âEnter a num: â);
num2= scan.nextInt();
System.out.println( 11 + maxOf(num1,num2) );
⢠If the user entered 50 and 61, the last line would
calculate 11 + 61, and print out 72
Š 2004 Pearson Addison-Wesley. All rights reserved 5-15
16. Designing Methods 1
⢠Methods are the basic components of any large
program
⢠With few exceptions, methods should
ď§ get their inputs as formal parameters, and return a result
if required,
ď§ not print anything out to the user, and
ď§ not get any input from the user
⢠The last 2 rules allow the caller of a method to
decide if they want to print something out to the
user
⢠However, it is legal to write a method to prompt a
user, get input and validate that input
⢠Similarly, if user output is complicated, then it's
OK to place the code in a method
Š 2004 Pearson Addison-Wesley. All rights reserved 5-16
17. Input Method Example
public static double getHeight()
{
double userheight;
Scanner scan = new Scanner (System.in);
while (true)
{
System.out.print(âEnter your height: â);
userheight= scan.nextDouble();
// Only accept if between 1.2m and 2.4m
if ((userheight>=1.2) && (userheight<=2.4))
return(userheight);
System.out.println(âTry again...â);
}
}
Š 2004 Pearson Addison-Wesley. All rights reserved 5-17
18. What's void?
⢠We have to declare what type of value a method
returns
⢠What if it never returns a value? We declare it to
return void, e.g.
public static void printGrade(int mark)
{
if (mark<50)
System.out.println(âFLâ);
else if (mark<65)
System.out.println(âPSâ);
else if (mark<75)
System.out.println(âCRâ);
else if (mark<85)
System.out.println(âDNâ);
else
System.out.println(âHDâ);
}
Š 2004 Pearson Addison-Wesley. All rights reserved 5-18
19. Methods Can Call Other Methods
⢠Methods contain ordinary Java code; this code
can call other methods
⢠This has been shown in the examples on the
previous slides, e.g
ď§ getHeight() called System.out.print()
and scan.nextDouble()
Š 2004 Pearson Addison-Wesley. All rights reserved 5-19
20. Method Control Flow
⢠When a method calls another method, execution of
the program diverts into that method
main doIt helpMe
obj.doIt(); helpMe();
Š 2004 Pearson Addison-Wesley. All rights reserved 5-20
21. Designing Methods 2
⢠The declaration of an a method is known as its
interface
⢠It describes how other methods use it
⢠When designing large programs, cut the task up
into sub-tasks, where a sub-task is done by one
method
⢠Design the interface to the method first:
ď§ what inputs does it need to do the job?
ď§ what result if any will it return?
⢠Once you know what each method will do, then
you can write the code for the method
⢠This gives you a broad idea of the solution, before
you have filled in the details
Š 2004 Pearson Addison-Wesley. All rights reserved 5-21
22. Design Time
⢠As a class, design declarations for these methods:
⢠A method to count the number of uppercase
letters in a string
⢠A method that, given a letter and a count, returns a
string with that many of the letters
⢠A method that indicates if a given number is a
prime (true) or is not a prime (false)
⢠A method to convert a Celsius temperature to
Fahrenheit
⢠A method that, given a string, indicates if the
string has no uppercase letters in it
⢠A method that, given a letter and a count, draws a
box using that letter. Each side has count letters
Š 2004 Pearson Addison-Wesley. All rights reserved 5-22
23. Design Time 2
⢠Now, write the full method to count the number of
uppercase letters in a string
⢠Hint: Use the existing methods in the String class,
especially length() and charAt()
⢠Hint: You need to check out each letter, so you will
need a loop. What type?
⢠Hint: Do you know the length of the string?
⢠Can you think of some inputs and outputs that will
show if the method is working correctly?
⢠Think of some very unusual strings to try out
Š 2004 Pearson Addison-Wesley. All rights reserved 5-23
24. Unit Testing
⢠All large programs have bugs: usual estimate is 1
bug per 100 lines of code
⢠Most bugs are logic bugs: the programmer thinks
it works, but the code does something different
⢠It's nearly impossible to tell if a program is 100%
bug-free
⢠Implication: programs should be tested thorougly
to give assurance there are no bugs
⢠Unit testing: test a method with a large set of
inputs, to ensure that it produces the correct
output
⢠The test set is designed to stress the method as
much as possible
Š 2004 Pearson Addison-Wesley. All rights reserved 5-24
25. Unit Testing
⢠You should design the method interface first
⢠THEN, construct a suitable test set for it
⢠ONLY THEN, write the actual method code
⢠Once you think you have written the method, you
can then test the method with the unit tests
⢠âCoding isn't complete until all the unit tests passâ
⢠ALWAYS generate the tests by hand. Don't use a
program to generate the test set. Why not?
⢠Bluej provides a framework to construct unit tests.
⢠You will see it in the labs, and you will be
assessed on its use
Š 2004 Pearson Addison-Wesley. All rights reserved 5-25