Title: G51PR1
1G51PR1
- Introduction to Programming I
- 2000-2001
- University of Nottingham
- Unit 5 Methods (functions)
2Overview
- Modularity
- Methods in Java
- Declaration Syntax
- Examples
- Definition
- Return Types
- Parameters
- Method Overloading
- Local Variables in methods
- Parameters by value
- Examples
- Circle radii and areas
- The ok method
- Mathematical methods
- Recursion
- The Tower of Hanoi
- Problem
- Solution
3Motivation the need for modularity.
- Methods enable us to break a program down into a
number of smaller units. This is taken one step
further later in the course with the idea of
classes and objects. There are several different
reasons why programs should be broken down in
these ways. - (i) Most problems naturally break down into
sub-problems. - (ii) Large problems must be implemented by a
team, not an individual. - (iii) Reusability of the parts, is highly
appreciated - For the program itself
- For other programs
4Motivation the need for modularity.
- Units which solve frequently occurring
sub-problems can be reused in appropriate places
in a variety of larger problems. - (i) They may be used in order to save effort in
re-solving that particular problem, and in
re-programming the solution. - (ii) They may be used in order to produce better
quality systems, on the assumption that the
solution being re-used was tested to a high
quality standard when it was originally written.
5Methods in Java
- Methods gives us the ability to break a program
into smaller parts. Later we will see that this
extends with the idea of classes and packages. - For those who have used other programming
languages, the concept of a method" in Java
corresponds to a function in C and "procedure"
or "subroutine" elsewhere. - We've seen the main method many times
6The method declaration
- The method declaration needs to inform the
compiler of (amongst other things) - 1 the identifier of the method (name)
- 2 the number and types of any parameters
(input) - 3 the type of result to be returned (output)
- 1. Some methods will return a result, some will
not. i.e. Methods to compute the square root of a
number will return a numeric result for use in
the program requesting the square root. A method
to print output will not return a numeric value. - 2. The identifier of a method follows exactly the
same rules as identifiers for variables. It must
not clash with the reserved words of the
language. - 3.We sometimes need to pass values into methods
when we call them. With the "square root" example
below, each time we call it we must give the
value of the number whose square root we require.
The number which we pass to it is some times
called a parameter and sometimes an argument.
7The syntax of a method
- A method consists of
- modifiers ltreturned typegt ltidentifiergt (
- ltparam typegt ltparam identgt,
- ltparam typegt ltparam identgt,
- ....
- )
- // fields and statements
- // a return statement
- // usually an end comment here
- The returned type may be any ordinary Java type
such as "int", "float" and so on, or "void" if no
value is being returned to the main program. - In some older programming languages, the word
function was used when a result was to be
delivered the word "procedure" or "subroutine"
was used is there was no result to deliver. In
Java all such items are called methods.
8A simple example of a method
- public class MethodExample
- // First the declaration and definition
- // of two methods
- static void dothis()
- System.out.println("Hello")
- // end of dothis
- static void dothat()
- System.out.println(Hello Again!")
- // end of dothat
9A simple example of a method
- // Now the program calls them
- public static void main(String argv)
- // These are the calls
- dothis()
- ....
- dothat()
- // end of main
- // end class MethodExample
- The parentheses following the method identifier
in the method calls in the main program indicate
that dothis and dothat are identifiers
representing methods to be executed. The methods
may, of course, be called as many times as you
wish within the program.
10Examples of methods
- public static double MyFunction (int
IntParameter, float FloatParameter ) - double MyLocalVariable
- MyLocalVariable IntParameter
FloatParameter - return MyLocalVariable
-
- public static int third_power (int number)
- int cube
- cube number number number
- return cube
- // method third_power
11Examples of method declarations
- A method to compute the power of 2 of a given
value. - // identifier power2"
- // takes one double parameter
- // gives double result
- double power2( double value)
- return valuevalue
-
- A method to detect the larger of two integer
values. - // identifier "max takes two integer parameters,
- // and gives an integer result
- int max( int arg1, int arg2)
- if (arg1gtarg2)
- return arg1
- else
- return arg2
12Examples of method declarations
- A method to print an error message involving an
integer value. - // identifier "error"
- // takes integer parameter, gives no returned
result - public static void error( int errorNumber )
- switch (errorNumber)
- case 1 System.out.println(Bad Command)
- break
- case 2 System.out.println(Wrong
parameters) - break
- .. .. ..
-
13Method calls
- The above methods would be called from elsewhere
(perhaps from main(), perhaps from another method
using similar statements. - To make a method call (to a method in the current
class) you simply name the method in an
appropriate statement and give actual parameters
(which will "take the place" of the formal
parameters).
14Example 1 Invoking a method
- Square root would take a "double" parameter and
return a double result. - double y sqrt ( 2.0 )
- ....
- if ( sqrt ( x 5 ) gt 2.0 )
- ....
-
- ....
- System.out.println("Sqrt " sqrt( 2.0 ) )
- We would normally expect to use the returned
result as a value.
15Example 2 Invoking a method
- int biggest, mark, nonNegative,first,second
- System.out.print("Please type in two numbers ")
- System.out.flush()
- first UserInput.readInt()
- second UserInput.readInt()
- biggest max( first, second )
- mark max( first, 40 )
- System.out.println("Larger value is " max (
first, second)) - nonNegative max( first, 0 )
16Example 3. Invoking a method
- // Reporting an error
- if ( n lt 0 )
- error ( 5 ) // no result
- else
- if ( n gt 100 )
- error ( 6 ) // no result
-
17Method Flow of Control
- The main method is invoked by the system when you
submit the bytecode to the interpreter - Each method call returns to the place that called
it
method2
main
method1
method2()
method1()
21
18The method definition
- The method definition needs to inform the
compiler of the actions to be taken when the
method is called. In order to describe the
actions to be taken when the method is called, we
need to identify each of the parameters, so that
we can refer to them and use them from within the
code which forms the body of the method. - If we need variables inside the body of the
method it is conventional to declare them at the
start of the body (apart from loop variables).
These are known as local variables and a new copy
of them is created every time a method is called
(invoked). - The rest of the body of the method is dedicated
to implementing the logic of the method so that
it performs the job we want it to. This can
include any legal statements we wish that help us
achieve our desired result. - At any point we can exit the method using a
return statement
19The "max" method
- // deliver the larger of the 2 params
- int max ( int i, int j )
- if ( i gt j )
- return i
-
- return j
- // end max
- //An alternative is to use the else construct.
- int max ( int i, int j )
- if ( i gt j )
- return i
- else
- return j
-
- // end max
- We want a method to deliver the larger of the
values of the two values given as parameters.
20The "max" method
- The "return" keyword acts both to specify the
particular value to be returned by the call of
the method, and to cause dynamic exit from the
method. - If the method returns type "void" we leave the
method using the statement return with
no value specified. - If the method returns a non-void type, the
"return" must be followed by a value of the
required type. - Notice that we do not need an "else" statement in
this example because of the dynamic exit caused
by the "return i" statement. However, it does
make the logic of the control explicit and may be
easier to read. With lots of return statements
dotted throughout the method the control flow can
be very cryptic.
21The "error" method
- We want a method to print an error message and
then abandon the program. - public static void error ( int errno )
- System.out.print( "Error number" )
- System.out.println( errno " has occurred" )
- System.out.println( "Program abandoned" )
- exit ( 1 )
- // end error
- In this example, the "exit" causes the whole
program to terminate if we merely wished to
report the error (say as a warning) and continue
the program, we would use a return statement
with no value given. - public static void warning ( int warno )
- System.out.print( "Warning number" )
- System.out.println( warno " has occurred" )
- System.out.println( "Program continues" )
- return
- // end warning
22The exit method
- Convention with the "exit" function is that
- exit( 0 ) // indicates normal exit
- exit( 1 ) // indicates error exit
- exit( 2 ) // indicates error exit
- The UNIX/Windows/etc shell can use the value
returned by a terminating program to determined
whether it terminated successfully or not. - The CourseMaster system will, in some exercises,
require you to use the "exit" method to indicate
errors in the data.
23Returned types
- The compiler needs to know the type of the value
to be returned by the methods so that it can be
treated correctly in the call of the method.If no
value is to be returned (like in "error" or
"dothis" above) then the return type is given as
"void". - The particular value to be returned is specified
by the line return ltvaluegt - With a "void" method you have the option of using
return
24Parameter types
- The parameter type sequence in the declaration
and the definition must agree. The compiler will
make the necessary type conversions to the
parameters and to the delivered result in a call
of the method. - Again, the compiler will perform type conversions
if the method declaration specifies a "float"
parameter, and if the call includes an actual
integer parameter. - Remember the parameters in the method definition
are called the formal parameters. The parameter
values supplied in calls of the method are called
actual parameters.
25Method overloading
- You can use the same method identifier for more
than one method, providing that the compiler can
determine the particular one to be chosen by the
types (and number) of its parameters. - int square ( int i )
- // int squared is an int
- return i i
-
- double square ( double x )
- // double squared is a double
- return x x
-
- double square ( double x, double height )
- // return the volume of a square prism
- return x x height
26Method overloading
- The calls might be
- i square( 3 )
- double z
- if ( square( z ) gt 3.14159 )
- ....
- vol square( z, 1.27 )
- The compiler would then look at each call of the
method, and determine from the types of the
parameters which of the definitions was to be
invoked. - The strict rules to define what parameter types
can be distinguished are very complicated the
best advice is just to make the difference very
obvious!
27Local variables
- We can declare local variables at the start of
our method code if we require additional
variables for computations within the method. The
declarations appear after the opening curly
brace, just as they do in main(). - If a local identifier clashes with a class
constant or variable, or with the name of another
method, then that global constant or other method
becomes inaccessible within this method. The
local object will be referred to by the
identifier. - final float pi 3.1416
- main()
- ...
- pi ... // global constant
- // end main
- int fred( int i )
- int pi // local variable
- pi ... // local variable
- // end fred
28Parameters called by value
- When a method is called, the values of the
(actual) parameters at the point where the method
is called are calculated, and passed to the
method definition for execution. Within the
method, the parameters act like variables,
initialised to the value of the corresponding
actual parameter at the call, and their values
can be changed by ordinary assignment. - Thus if a method definition is
- int fred( int number )
- ....
- number number p
- ....
- // end method fred
- the identifier "number" can be considered as a
local variable to the method. Changing its value
inside the method as shown in the above example
has no effect on the outside world.
29Example
- int count( int value )
- ....
- for ( value gt 0 value-- )
- ....
- // end for loop executed "value" times ....
- // end method fred
- If the call of the method is
- int counter ...
- fred( counter )
- the value of the variable "counter" in the
calling program will not be changed. We could
also call the method by - fred( 23 )
- which would pass the value 23 to the formal
parameter. This way of passing parameters is
referred to as "passing by value".
30A complete example
- The "Halberstam Function" of an integer value is
defined as follows - Given a positive integer value, generate the
sequence - If it is even, half it.
- Otherwise multiply by 3 and add 1.
- The Halberstam value of an integer value "n" is
the number of times this operation needs to be
repeated before the value 1 (one) is reached. - It is guaranteed that you will eventually reach
the value 1. - If we start with the value 3, for example, the
sequence goes 10, 5, 16, 8, 4, 2, 1 7 steps. - If we start with the value 7, the sequence goes
22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8,
4, 2, 1 16 steps. - A complete program with function and main program
will look roughly as follows. We use an example
with the Halberstam function. - main prompts the use for a starting value and
prints the result.
31Halberstam Solution
- // Halberstam function, by Eric Foxley and Colin
Higgins - import java.lang.
- public class Halberstam
- static int halberstam( int numb )
- int calcs 0
- // Error exit
- if ( numb lt 0 )
- return -1
-
- // Loop counting how many times
- while ( numb ! 1 )
- if ( numb 2 ) // number is odd
- numb 3
- numb
- else // number is even
- numb / 2
-
- calcs
- // End of while loop
32Halberstam Solution
- // The main program
- public static void main()
- int numb 0, calcs 0
- // get the first value in
- System.out.print("Enter the number now please
") - System.out.flush()
- numb UserInput.getInt()
- // Loop reading integers until we meet a
zero - while ( numb ! 0 )
- calcs halberstam( numb ) // This is the
call - System.out.print( "numb " numb )
- System.out.println( " result " calcs )
- System.out.print("Enter the number now
please ") - System.out.flush()
- numb UserInput.getInt()
- // end while number gt 0
- // end main program
- // end class Halberstam
33Circle radii and areas
- We show here two methods taking "float"
parameters, and giving "float" results. The first
takes a radius length, and delivers the area of a
circle of that radius. The second takes an area,
and delivers the radius of a circle with that
area. - static final float PI 3.14159f
- static float area( float radius )
- return PI radius radius
- // end radius to area
- static float radius( float area )
- if ( area lt 0 )
- error( "Sqrt invalid param " area )
-
- return sqrt( area / PI )
- // end area to radius
Calls of these functions might be float a1, r1,
a2, r2 r1 UserInput.readFloat() a1 area( r1
) a2 UserInpit.readFloat() r2 radius( a2
) if ( r2 lt 0 ) ...
34The ok method
- We require a method to print out a given message
as a question, and return true if the user
replies "y" and false otherwise. The type of a
message (a string of text contained within double
quotes) is a String , and the definition of the
method might be - static boolean ok( String message )
- char ch
- System.out.print( message " Type y or n?
" ) - System.out.flush()
- ch UserInput.readChar()
- return ch 'y'
-
- In a real situation, the method body might repeat
the question until the given answer is "y" or
"n". In the above example, we respond with true
if the answer is "y" and false otherwise.
Note that we do not need to say if ( ch 'y'
) return 1 else return
0
35The OK method
- We can return the comparison result directly.
- Calls of this function might be
- if ( ok( "Was that correct" ) )
- ....
- else
- ....
-
- if ( ok ( "Overwrite the file" ) ok ( "Are you
sure" ) ) .... -
- Observe the subtlety of the last example. The
program first asks Overwrite the file Type y or
n? and, because the "" operator is lazy, only
if the reply to the first question is "y" asks
for confirmation Are you sure Type y or n? If
the reply to the first question is "n", the
second question is not asked.
36Mathematical methods
- A number of standard mathematical methods are
available. For details see the java.lang.Math
class.
Basic numerical operations (Equivalent to Cs
ltmath.hgt) exponentials logarithms
square roots trigonometrics etc. etc.
Examples abs pow, sqrt log, exp
sin, cos, tan asin, acos, atan floor,
ceil, round max, min random
37Recursion
- "Recursion" occurs when you invoke a method
within itself. Obviously you must be careful not
to let the method to recurse indefinitely
(infinitely), so a recursive method will usually
have an "escape clause" such as "if ( n lt 1 )
... " - Factorial Example
- Consider a method which will produce the
factorial of a positive integer value, where
factorial(n) is defined as
n (n-1) (n-2) 2 1. - We could do this with a for loop. However, this
problem is more naturally solved recursively. - We note that another way of defining factorial is
if (n 1) factorial(n) 1 otherwise
factorial(n) n factorial(n 1)
38Solution
- public static int factorial( int n )
- if ( n 1 )
- return 1
- else
- return n factorial( n 1 )
-
-
39The Tower of Hanoi problem.
- The problem is to get all the disks on one tower
to another tower, moving one disk at a time and
only being allowed to put a small disk on a
larger one. There is a third tower available as a
"temporary" resting place for disks. - Solution
- Number the towers 1 2 3.
- Start with 64 disks on 1. We need to move them to
3. - Denote this task by movetower( 64, 1, 3)
- We need to provide a list of correct moves to
solve the problem. The insight is to think about
the bottom disk on tower 1 rather than the top
disk. movetower( 64, 1, 3 ) can be achieved by - movetower( 63, 1, 2 )
- move a disk from 1 to 3
- movetower( 63, 2, 3 )
1
2
3
40The Tower of Hanoi problem.
- Now movetower( 63, 1, 2 ) can be achieved by
- movetower( 62, 1, 3 ) and move a disk from 1 to 2
and movetower( 62, 3, 2 ) - To construct a general algorithm we need to
specify which tower to use as a - temporary tower. So movetower( n, a, b, c) means
- move n disks from a to b using c as the temporary
tower. - movetower( n, a, b, c) can then be performed by
the following three steps - movetower( n-1, a, c, b )
- move a disk from a to b
- movetower( n-1, c, b, a )
- We need to cope with nlt1 so add the rule
- if n lt 1 do nothing.
1
2
3
41The Tower of Hanoi program
- public class Hanoi
- public static void movetower(int height, int
fromT, int toT, int usingT) - if ( height gt 0 )
- movetower( height 1, fromT, usingT, toT )
- moveDisk( fromT, toT )
- movetower( height 1, usingT, toT, fromT )
-
- //end moveTower
-
- void moveDisk( int takeoff, int puton )
- System.out.println( takeoff "-gt" puton )
- // end moveDisk
1
2
3
42The Tower of Hanoi program
- public static void main()
- int numberOfDisks
- System.out.print("how many disks? ")
- System.out.flush()
- numberOfDisks userInput.getInt()
- movetower( numberOfDisks, 1, 3, 2)
- // end main
- end class Hanoi
- To learn more about this interesting solution
look at http//www.lhs.berkeley.edu/Java/Tower/t
owerhistory.html
1
2
3
43Summary
- Modularity
- Methods in Java
- Declaration Syntax
- Examples
- Definition
- Return Types
- Parameters
- Method Overloading
- Local Variables in methods
- Parameters by value
- Examples
- Circle radii and areas
- The ok method
- Mathematical methods
- Recursion
- The Tower of Hanoi
- Problem
- Solution