Introduction to Methods

advertisement
Introduction to Methods
CS0007: Introduction to Computer Programming
Methods
 So far in this course we have seen methods in two ways:
 We’ve used predefined methods from the Java API:
 System.out.println
 Math.sqrt
 We have created a method named main in every program we’ve
written.
 Now we will learn to create our own methods that can be used
just like any from the Java API.
 So what are methods exactly?
 Methods are a collection of statements that perform a specific task.
 Why do we have methods?
 Methods break problems in smaller, more manageable, subproblems.
 Where have we seen this before?
 Hierarchy Charts!
Methods and Hierarchy Charts
Postage Stamp
Program
Calculate
Stamps
Input
Read Sheets
Validate Sheets
Set Stamps =
Sheets/5
Round Stamps to the
next whole number
Display Stamps
Divide and Conquer and Modular
Design
 Instead of writing one long method that contains all of the statements
necessary to solve a problem, you can write several small methods that
solve each specific part of the problem.
 This is what is known as divide and conquer approach to programming.
 When you use divide and conquer to design a program, this is known as Modular
Design.
 As a result, each subproblem is known as a module.
o These modules can easily be implemented as their own methods!
 Programs that follow modular design principles have benefits:
1. They are easier to write.
2. They are easier to understand.
3. They are easier to debug.
4. They are easier to change.
5. They have parts that can be reused.
 After learning about methods, you are required to design and implement your
programs according modular design principles.
void Methods and Value-Returning
Methods
 The reason why these structures are called methods is because they
reside in classes.
 This is because in Java almost everything resides in a class.
 In other Non-Object-Oriented languages, we would call these structures
functions and subprocedures, but instead we call them void methods and
value-returning methods.
 void methods simply perform a task then terminate.
 value-returning methods not only perform a task, but also send a value back to the
code that called it.
 For example:
 You can perform all output in a void method because it doesn’t require and result
to be used.
 Math.sqrt returns a value back to where it was called (For instance,
Math.sqrt(9) returns 3 to where it was called).
 Key terms:
 Call
 Return
Method Definition
 Before you can use a method you must define it.
 A method definition has two parts:
 Method header – appears at the beginning of the method
definition and several important things about the method
 Method body – the collection of statements to be executed
when the method is called. It is enclosed in curly braces.
 Again, we’ve seen this before:
public static void main(String[] args)
{
...
}
Method Definition
 General form of a method:
methodModifiers returnType name (parameterList) {
body
}
 methodModifiers – Keywords that define specific attributes about
the method.
 returnType – If the method is value-returning the data type of the
returned value goes here. If it is a void method, the keyword void goes
here.
 name – Any valid identifier that will be used as the name of the method.
Again, it should be descriptive of what the method does, and often should be
a verb.
 parameterList – Methods are capable of receiving outside
information called arguments. They are assigned to the method’s
parameters. If the method does not receive any arguments, there is nothing
inside of the parentheses. We will discuss arguments and parameters later.
Method Example
public static void displayMessage(){
System.out.println("Hello from
the displayMessage method!");
}
 public and static are method modifiers. In short
public makes the method available for use outside of the
class, and static means that it belongs to the class itself and
not individual objects.
 void is the return type meaning this method does not return a
value.
 displayMessage is the name of the method
 This method does not take any arguments.
Method Call
 A method is only executed when called.
 The only exception to this is the main method, which is
executed when the program is run.
 When the JVM sees a method call, it branches to the
statements inside of the method.
 To call a method, you must use its name and supply it with
arguments if the method expects them.
 General form of a method call:
name(argumentList);
 If the method definition has nothing for its parameter list,
then you do not need to supply an argument list.
Method Example
 New Topics:
 Methods
Arguments and Parameters
 Methods declared outside of one another have different scope:
public static void method1() {
int x;
method2();
}
public static void method2() {
int y;
}
 method2 cannot see method1’s local variable x, even though method2 is
called from method2. Similarly, method1 cannot see method2’s local
variable y.
 General Rule: Local variables declared inside of a method cannot be seen outside of the
method it was declared in.
 So how can methods pass data from one to another?
 First part of the answer: the caller can pass data to the callee in the form of arguments.
o An argument is data passed to a method during a method call.
Arguments and Parameters
 We’ve passed arguments to methods before:
System.out.println("Hello");
Math.sqrt(9);
 "Hello" and 9 are data we passed the println and
sqrt methods that is used to perform their desired functions.
 These arguments are then stored as local variables that can be
used corresponding definition.
 These local variables are called parameters.
 Parameters appear in the method header and can be used anywhere in the
method definition.
Arguments and Parameters
public static void method1() {
int x = 5;
method2();
}
public static void method2() {
int y = x;
}
method2() cannot see x because it is out of scope, so this is an error.
Arguments and Parameters
public static void method1() {
int x = 5;
method2(x);
}
public static void method2(int myX) {
int y = myX;
}
 method1 passes the local variable x as an argument
 method2 takes an integer parameter called myX
 When method1 calls method2, the value stored in x is sent to the
parameter myX so that method2 can use it.
 Note: arguments can be any expression that resolves to the type that
corresponds to the called method’s parameter.
Arguments and Parameters Example
 New Topics:
 Arguments and Parameters
Argument and Parameter Notes
 Terminology varies for what people call arguments and parameters, but
what is important is that you remain consistent.
 The argument must be some expression that is of the same type as the
corresponding parameter OR some type of lower rank.
 Java will automatically perform widening conversions.
 Java WILL NOT perform narrowing conversions.
 Parameters have the same scope as local variables declared in the
method.
 To pass an array variable as an argument, you can simply pass the
variable by name.
 The corresponding method parameter looks very much like a normal
parameter, but with [] between the parameter data type and the parameter
name
 There are many, many more nuances to arguments and parameters, but
we will cover them later.
Passing Multiple Arguments
 Java also allows for the passing of multiple arguments to a single
method:
public static void method1() {
method2(1, 2);
}
public static void method2(int x, int y){ int z =
x + y;
}
 The arguments in the method call, as well as, the parameters in the method
header are both separated by commas.
 The argument’s values are passed to the corresponding parameters in the order
in which they are arranged from left to right.
 For example, x would get the value 1 here and y would get the value 2.
 Example: MultipleArgs.java
Returning Values
 Methods may also pass data back to where it was called.
 This is called returning a value.
 We’ve seen this before:
Math.sqrt(9)
 This method call returns the value of 3 back to where it was called.
 There are two differences when writing value returning methods:
 Instead of void as the return type, now that should be whatever
type the value you want to return will be
 You must use a return statement to return a value at some point for
all possible branches in the method definition.
Returning Values
public static int addOne(int x) {
return x+1;
}
 The int after static indicates that this method will return a value of
type int.
 return x+1; is a return statement.
 return is a keyword that indicates that the result of the expression following it will
be returned to where the method was called
 So in this case, the result of x+1 will be returned to where it was called
 You can have as many statements as you like leading up to the return statement, but
all branches that are possible in the method definition should end in a return
statement.
 Once a return statement is reached, the program’s control flow leaves the method
and goes back to where it was called.
 The expression following the return statement must be the same type as the return
type for the method, or one of a lower rank.
Calling a Value-Returning Method
 Its often the case that you want to do something meaningful
with the value a value-returning method returns.
 You can assign the return value to a variable:
double x = Math.sqrt(9);
 You can use it in an expression:
double x = Math.sqrt(9) * 2;
 You can print it to the screen
System.out.println(Math.sqrt(9));
 You can use it anywhere a value of the return type can be used
Value-Returning Method Example
 New Topics:
 Value-Returning Method
Download