Download Methods

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
MIT-AITI 2003 Lecture 6
Methods
Methods
The Concept of a Method

Methods also known as functions or procedures.

Methods are a way of capturing a sequence of
computational steps into a reusable unit.

Methods can accept inputs in the form of
arguments, perform some operations with the
arguments, and then can return a value the is
the output, or result of their computations.
inputs
outputs
method
Square Root Method

Square root is a good example of a method.

The square root method accepts a single number as an
argument and returns the square root of that number.

The computation of square roots involves many
intermediate steps between input and output.

When we use square root, we don’t care about these
steps. All we need is to get the correct output.

Hiding the internal workings of a method from a user but
providing the correct answer is known as abstraction
Declaring Methods

A method has 4 parts: the return type, the
name, the arguments, and the body:
type
body

name arguments
double sqrt(double num) {
// a set of operations that compute
// the square root of a number
}
The type, name and arguments together is
referred to as the signature of the method
The Return Type of a Method

The return type of a method may be
any data type.

The type of a method designates the
data type of the output it produces.

Methods can also return nothing in
which case they are declared void.
Return Statements

The return statement is used in a method to output
the result of the methods computation.

It has the form: return expression_value;

The type of the expression_value must be the
same as the type of the method:
double sqrt(double num){
double answer;
// Compute the square root of num and store
// the value into the variable answer
return answer;
}
Return Statements

A method exits immediately after it
executes the return statement

Therefore, the return statement is
usually the last statement in a method

A method may have multiple return
statements. Can you think of an
example of such a case?
Brain Teaser Answer

Example:
int absoluteValue (int num){
if (num < 0)
return –num;
else
return num;
}
void Methods

A method of type void has a return statement
without any specified value. i.e. return;

This may seem useless, but in practice void is
used often.

A good example is when a methods only
purpose is to print to the screen.

If no return statement is used in a method of
type void, it automatically returns at the end
Method Arguments

Methods can take input in the form of
arguments.

Arguments are used as variables inside the
method body.

Like variables, arguments, must have their
type specified.

Arguments are specified inside the parentheses that follow the name of the method.
Example Method

Here is an example of a method that
divides two doubles:
double divide(double a, double b) {
double answer;
answer = a / b;
return answer;
}
Method Arguments

Multiple method arguments are
separated by commas:
double pow(double x, double y)

Arguments may be of different types
int indexOf(String str, int fromIndex)
The Method Body

The body of a method is a block
specified by curly brackets. The body
defines the actions of the method.

The method arguments can be used
anywhere inside of the body.

All methods must have curly brackets
to specify the body even if the body
contains only one or no statement.
Invoking Methods

To call a method, specify the name of
the method followed by a list of comma
separated arguments in parentheses:
10
pow(2, 10); //Computes 2

If the method has no arguments, you
still need to follow the method name
with empty parentheses:
size();
Static Methods

Some methods have the keyword
static before the return type:
static double divide(double a, double b) {
return a / b;
}

We'll learn what it means for a method
to be static in a later lecture

For now, all the methods we write in lab
will be static.
main - A Special Method

The only method that we have used in lab up
until this point is the main method.

The main method is where a Java program
always starts when you run a class file with
the java command

The main method is static has a strict
signature which must be followed:
public static void main(String[] args) {
. . .
}
main continued
class SayHi {
public static void main(String[] args) {
System.out.println("Hi, " + args[0]);
}
}

When java Program arg1 arg2 … argN is typed on
the command line, anything after the name of the class file
is automatically entered into the args array:
java SayHi Sonia

In this example args[0] will contain the String "Sonia",
and the output of the program will be "Hi, Sonia".
Example main method
class Greetings {
public static void main(String args[]) {
String greeting = "";
for (int i=0; i < args.length; i++) {
greeting += "Jambo " + args[i] + "! ";
}
System.out.println(greeting);
}
}

After compiling, if you type
java Greetings Alice Bob Charlie
prints out "Jambo Alice! Jambo Bob! Jambo Charlie!"
Recursive Example
class Factorial {
public static void main (String[] args) {
int num = Integer.parseInt(args[0]));
System.out.println(fact(num));
}
static int fact(int n) {
if (n <= 1) return 1;
else return n * fact(n – 1);
}
}

After compiling, if you type java Factorial 4
the program will print out 24
Another Example
class Max {
public static void main(String args[]) {
if (args.length == 0) return;
int max = Integer.parseInt(args[0]);
for (int i=1; i < args.length; i++) {
if (Integer.parseInt(args[i]) > max) {
max = Integer.parseInt(args[i]);
}
}
System.out.println(max);
}
}

After compiling, if you type java Max 3 2 9 2 4
the program will print out 9
Summary

Methods capture a piece of computation we wish to
perform repeatedly into a single abstraction

Methods in Java have 4 parts: return type, name,
arguments, body.

The return type and arguments may be either
primitive data types or complex data types (Objects)

main is a special Java method which the java
interpreter looks for when you try to run a class file

main has a strict signature that must be followed:
public static void main(String args[])