View
216
Download
0
Embed Size (px)
Citation preview
Methods
Liang, Chapter 4
What is a method?A method is a way of running an ‘encapsulated’ series of commands.
• System.out.println(“Whazzup”);• JOptionPane.showMessageDialog(null, “Hello!”);• Name=JOptionPane.showInputDialog(null,“Who’re you?”);• int i=Math.pow(3,2);• main(String[] args) {....}
These methods give us a simple way of getting Java to do complicated things (other programmers have written code in the method which does those things)
We’ve already used methods that’re part of java(written by other programmers)
Now its time to write our own methods..........
When calling a method (we’ve done this before)
JOptionPane.showMessageDialog(null,“Hello”);
What Class the method belongs to
The name of the method we’re calling
Arguments to the method (in brackets)
Name=JOptionPane.showInputDialog(null,“who’re you?”);
What Class the method belongs to
The name of the method we’re calling
Arguments to the method (in brackets)
Data returned by the method goes here
This method does something:
This method does something and returns a value:
Writing the code for a method
• A method needs to be defined (write its code and give it a name)
• The definition has a header and a body
• The header specifies:
– which pieces of code can use the method (public /private etc.)
– what the return type of the method is (what type of data it returns)
– the method’s name
– the arguments or parameters passed to the method when it is called
Example: maxWe will create method to return the maximum of two integers
Here’s an example of calling this method
int i = 5;
int j = 3;
int k = max(i, j);
System.out.println(“k is “ + k);
This method max gets the highest of the two arguments passed in, and returns it (in this case, to the int k).
I’ve left out the name of max’s class here for the moment! I’ll explain soon…
The method headerpublic static int max(int num1, int num2)
modifiers
return type
method name
parameters
each parameter has a type and a name.
This tells us that method max is public, takes two integers as arguments (within the method these will be called num1 and num2), and returns an integer as its answer.
The method maxpublic static int max(int num1, int num2) {
int result = 0;
if(num1 > num2) {
result = num1;
} else {
result = num2;
}
return result;
}
This code works out which of num1 or num2 is higher, and puts the answer in the result variable
This line returns the contents of the result variable to the user as the answer from this method.
The method header says an int must be returned: the result variable is an int.
Max in a Class ( a program)public class Fintan {
public static int max(int num1, int num2) { int result = 0; if(num1 > num2) { result = num1; } else { result = num2; } return result;}
public static void main (String[] args) { int i = 4; int j = 8; int k = Fintan.max(i, j); System.out.println(k);}
}
The max method is defined inside a class called Fintan
This is the main method of the class Fintan.
We call max by giving the class it is part of, the method name, and its arguments.
Calling a methodIf a method returns a value, then a call to that method produces a value of the returned type:
int larger = Fintan.max(4, 8);
We can use a call to the method anywhere that a value of that type is appropriate:
System.out.println( Fintan.max(4, 8));
If the method is defined in some other class (program) we wrote, we have to give the name of that class (as in Fintan.max(4, 8) )
If the method is defined in the current class, we don’t need to give the class name; java can guess. In class Fintan we can just say max(4, 8) if we like. (Java knows we mean Fintan.max(4,8))
Methods without a return type
• Some methods do not return a value.
• In the method header, the return type is given as void
• If a method does not have a return value, then presumably it does something else which is of potential use, e.g........
• System.out.println(“whoopie”);
• When a method call is reached, code execution carries on at the start of the method body
• When the end of the method body (or a return statement) is reached, the flow of control returns to the point at which the method was called.
Testing maxpublic class Fintan {
public static int max(int num1, int num2) { int result = 0; if(num1 > num2) { result = num1; } else { result = num2; } return result;}
public static void main (String[] args) { int i = 4; int j = 8; int k = max(i, j); System.out.println(k);}
}
I didn’t bother with Fintan. here, just to save typing.
// in the main method
int i = 4;
int j = 8;
int k = max(i, j);
System.out.print(k);
// the max method
public static int max(int num1, int num2) { int result = 0; if(num1 > num2) { result = num1; } else { result = num2; } return result;}
When max is called, the variable num1 (in the method definition) gets the value 4, and the variable num2 gets the value 8.
That main method
public static void main(String[] args)
modifiers
return type
name
parameter (an array of Strings)
Passing parameterspublic static void nPrintLn(String s, int n) {
for(int i=0; i<n; i++) {
System.out.println(s);
}
}
nPrintLn(“Hi mom”, 4); // ok
nPrintLn(“”, 0); // ok, but pointless
nPrintLn(3, “Hi”); // not ok
Actual parameters must match formal parameters in type, order and number........
passing by value
• When a method call is reached, a copy of the actual parameters is made
• Within the method body, these copies are used
• No change in the original values can be made
• The value of the parameters are used
pass-by-valueint i = 5;
int j = 3;
System.out.printLn(“i: “ + i + “ j: “ + j);
swap(i, j); // swap tries to swap the contents of i and j
System.out.printLn(“i: “ + i + “ j: “ + j);
1. What would swap look like?
2. What will this code print?
3. Will swap work?
// in our main method
int i = 5;
int j = 3;
swap(i, j);
// our swap method
...void swap(int n1, int n2)
i j n1: copy of i n2: copy of j
n1 n2
5 3 5 3
3 5
5 3
i j
Overloading methods
• Our max method only works with parameters of type int.
• Its signature consists of the method name (max) and the formal parameters
(int num1, int num2)
• What if we want to find the maximum of two double values?
Two versions of max// max for integers
public static int max(int n1, int n2).....
// max for doubles
public static double max(double n1, double n2)...
When we call one of these methods, if is clear from the parameters we pass which one we mean.......
Example 4.3, p. 125
Tips on overloading methods
• Methods that do essentially the same thing should have the same name
• Overloaded methods must differ in their parameter lists
• You cannot have two methods with the same name, same parameter lists and different return types
Method Abstraction
input (optional) return value (optional)
method signature
method body
implementation
(black box)
Signature vs implementation
• Knowing the method signature (and return type) ought to be enough to allow you to use a method
• Typically, you should not care about how a method has been defined by someone else
• Abstraction (separation of the public face from the private implementation) is essential for software design
Example: the Math class
public static double sin(double radians)
public static double cos(double radians)
public static double sqrt(double a)
// returns e to the power of a
public static double exp(double a)
// returns log (base e) of a
public static double log(double a)
// the next 2 have different signatures
public static double pow(double a, double b)
public static int pow(int a, int b)
Math.random()
public static double random()
• Returns a double in the range [0..1)
• Each value in that range is equally likely to be generated (uniform distribution)
• How would you generate a number in the range –2..2?
• How could you generate a random integer in 1..10?
Case study 4.4, p. 132....
• Study this example carefully• Illustrates use of Math.random, Math.round,
Math.pow, and Math.sqrt• Computes the mean and the standard deviation
of a series of random numbers• mean = “average”• standard deviation: a measure of the amount of
variability in the set of numbers