Title: Methods Ch 5
1Methods Ch 5
- A design technique referred to as stepwise
refinement (or divide and conquer, or functional
decomposition) is used to break a problem down
into smaller more manageable pieces. In OO
programming these pieces are typically classes
and methods. - If a specific task is performed in several places
in the program, a method can be written once to
perform that task, and then be executed anytime
it is needed. This is known as code reuse.
2Method Types
- Methods can be
- Void, or
- Value-returning
- A void method is one that simply performs a task
and then terminates. For example println() is a
method that does not return anything to its
caller. - System.out.println(Hi!)
- A value-returning method not only performs a
task, but also sends a value back to the code
that called it. For example, parseInt() returns
an integer value found in the string passed to as
an argument. - int number Integer.parseInt(700)
3Void methods
- Recall the BlueJ shapes project
- Each class has several methods
- these methods happen to be void methods they do
something and then return to the point after they
were called.
4Defining a method
- A method has a header and a body.
- The method header lists important things about
the method - The method body is a collection of statements
that are performed when the method is executed.
public void changeColor (String newColor)
color newColor draw()
5Methods
- Method modifiers
- publicmethod is publicly available to code
outside the class - staticmethod belongs to a class, not a specific
object. E.g. the main() methods we have used. - Return typevoid or the data type from a
value-returning method - Method namea name that is descriptive of what
the method does - Parenthesescontain parameter specifications - a
list of variable declarations.
6Using methods
- A method executes when it is called.
- The main method is automatically called when a
program starts, but other methods are executed by
method call statements. - displayMessage()
- System.out.println(enter a student number)
Name of method
An argument
Name of an object
7Method documentation
- A method should always be documented by writing
comments that appear just before the methods
definition. - The comments should provide a brief explanation
of the methods purpose. - The documentation comments begin with / and end
with /. - Parameters _at_param
- Return value _at_return
- Lets examine shapes and the generated
documentation
8Passing Arguments to a Method
- Values that are sent into a method are called
arguments. - System.out.println(Hello)
- number Integer.parseInt(str)
- The data type of an argument in a method call
must correspond to the variable declaration in
the parentheses of the method declaration. The
parameter is the variable that holds the value
being passed into a method. - By using parameter variables in your method
declarations, you can design your own methods to
accept data passed to them. - Arguments must be passed to a method in the same
order they are declared
9Arguments are Passed by Value
- In Java, all arguments of the primitive data
types are passed by value. This means that only a
copy of an arguments value is passed into a
parameter variable. - If a parameter variable corresponding to a
primitive data type is changed inside a method,
it has no affect on the original argument.
10Passing String Object References to a Method
- Recall that a class type variable does not hold
the actual data item that is associated with it,
but holds the memory address of the object. A
variable associated with an object is called a
reference variable. - When an object, such as a String is passed as an
argument, it is actually a reference to the
object that is passed.
11Passing a Reference as an Argument
Warren
showLength(name)
- public static void showLength(String str)
-
- System.out.println(str is str.length()
characters long.) - str Joe //see next slide
The address of the object known as name is copied
into the str parameter. Both variables refer to
the same object the same location in memory
12Strings are Immutable Objects
- Strings are immutable objects, which means that
they cannot be changed. When the line - str Joe
- is executed, it cannot change an immutable
object, so new object is created to hold Joe
PassString.java
13_at_param Tag in Documentation Comments
- You can provide a description of each parameter
in your documentation comments by using the
_at_param tag. - General format
- _at_param parameterName Description
14More About Local Variables
- A local variable is declared inside a method and
is not accessible to statements outside the
method. - Different methods can have local variables with
the same names because the methods cannot see
each others local variables. - A methods local variables exist only while the
method is executing. When the method ends, the
local variables and parameter variables are
destroyed and any values stored are lost. - Local variables are not automatically initialized
with a default value and must be given a value
before they can be used. - Example LocalVars.java
15Value-Returning Methods
- Data can be passed into a method by way of the
parameter variables. Data may also be returned
from a method, back to the statement that called
it. - int num Integer.parseInt(700)
- The string 700 is passed into the parseInt
method. - The int value 700 is returned from the method and
stored into the num variable.
16Defining a Value-Returning Method
- public static int sum(int num1, int num2)
-
- int result
- result num1 num2
- return result
Return type
The return statement causes the method to end
execution and it returns a value back to the
statement that called the method.
This expression must be of the same data type as
the return type
17_at_return Tag in Documentation Comments
- You can provide a description of the return value
in your documentation comments by using the
_at_return tag. - General format
- _at_return Description
- Example ValueReturn.java
- The _at_return tag in a methods documentation
comment must appear after the general
description.The description can span several
lines.
18Returning a booleanValue
- Frequently, we need to write methods to test
arguments for validity and return true or false - Public static boolean isValid(int number)
- boolean status
- If(number gt 1 number lt 100)
- status true
- else
- status false
- Return status
-
- Calling code
- int value 20
- If(isValid(value))
- System.out.println(The value is within range)
- else
- System.out.println(The value is out of
range)
19Returning a Reference to a String Object
John
Martin
- customername fullName(John, Martin)
- public static String fullName(String first,
String last) -
- String name
- name first last
- return name
-
-
References to the strings are passed to first and
last.
The name John Martin is stored in memory and a
reference to it is in variable name
John Martin
The return statement sends a copy of the
reference back to the call statement and because
of the assignment statement, that reference is
stored in customername.
Example ReturnString.java
20Problem Solving with Methods
- A large, complex problem can be solved a piece at
a time by methods.
21Problem Solving with Methods
SalesReportWithScanner.java
Problem We want to report the average daily
sales for the sales amounts recorded in a
file. The name of the file is supplied by the
user.
- Outline of Solution
- Get name of file from user
- Read the file calculating the total sales for a
known number of days - Calculate and report the average
Methods getFileName() getTotalSales() display
Results()
22Problem Solving with Methods
Our main() method will call the other 3 methods
main()
getFileName()
displayResults()
getTotalSales()
23ASIDE a UML sequence diagram showing methods
calls
A class or an objects lifeline
SalesReport
main()
main() begins execution. When main() calls
getFileName(), main() is suspended and waits till
getFileName() completes. When getFileName()
returns, a value is assigned to filename. main()
resumes execution. main() calls getTotalSales()
and main() is suspended again. getTotalSales()
executes. When it finishes, a value is assigned
to totalSales. main() resumes execution. main()
calls displayResults(). main() is suspended
until displayResults finishes. main() resumes
execution at the statement following the
call. main() ends and the program stops.
filenamegetFileName()
Activation box indicates when getFileName() is
active. i.e. the period of time that its local
variables exist
totalSalesgetTotalSales()
These are called activation boxes representing a
period of time a method is active (executing or
suspended)
Activation box indicates when getTotalSales() is
active. i.e. the period of time that its local
variables exist
displayResults()
Activation box indicates when displayResults() is
active. i.e. the period of time that its local
variables exist
24Calling Methods that Throw Exceptions
- Note that the main() and getTotalSales() methods
in SalesReport.java have a throws IOException
clause. - exceptions are covered in Chapter 12.