Lesson 1.8 · Unit 1 · CED topic 1.9
Method signatures
A method is a named block of code that only runs when it is called. You have been calling methods since the first lesson (System.out.println is one), and in this lesson you learn to read the line that describes a method, its signature, closely enough to know exactly how to call it and exactly what you get back.
Learning objectives.
- 1.9.A. Identify the correct method to call based on documentation and method signatures.
- 1.9.B. Describe how to call methods.
Essential knowledge.
- 1.9.A.1. A method is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces. Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
- 1.9.A.2. A parameter is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.
- 1.9.B.1. A void method does not have a return value and is therefore not called as part of an expression.
- 1.9.B.2. A non-void method returns a value that is the same type as the return type in the header. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
- 1.9.B.3. An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
- 1.9.B.4. Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
- 1.9.B.5. A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.
Why methods exist
Naming a block of code lets you use it by name, as many times as you want, without rewriting it. That is procedural abstraction: you can use a method knowing what it does even if you do not know how it was written. A block of code is any section of code enclosed in braces.
Parts of a method header
public static double average(int sum, int count)
public staticare modifiers; Lesson 1.10 explainsstatic.doubleis the return type: the type of value the method gives back. A method that gives back nothing saysvoid.averageis the name.(int sum, int count)is the parameter list. A parameter is a variable declared in the header and usable inside the body. It receives a value when the method is called.
The method signature is the name together with the ordered list of parameter types. For the method above it is average(int, int). A method without parameters has an empty parameter list, such as reset(). The return type is not part of the signature.
Calling a method
An argument is the value passed into a method when it is called. The arguments must be compatible in number and order with the parameter types in the signature. Arguments are passed using call by value: each parameter is initialized with a copy of the argument, so changing the parameter inside the method never changes the caller's variable.
Methods live inside a class. The examples in this lesson leave out the public class Main { ... } wrapper to keep them short.
public static double average(int sum, int count) {
return (double) sum / count;
}
public static void main(String[] args) {
int total = 17;
int n = 4;
double result = average(total, n);
System.out.println(result);
}
4.25
### void and non-void
- A void method has no return value, so it is called as a statement by itself and is never part of an expression.
- A non-void method returns a value of the type named in its header. To use that value, store it in a variable or use it as part of an expression. Calling it as a statement and ignoring the result is legal but wastes the result.
### Overloading
Methods are overloaded when there are several methods with the same name but different signatures. Java picks the version whose parameter types match the arguments. Two methods that differ only in return type are not allowed, because the signature does not include the return type.
### The flow of control
A method call interrupts the sequential execution of statements: the program first runs the statements in the method, then continues at the point immediately after the call. The method ends when its last statement runs or when a return statement runs.
Match each call to a method, or say why none matches.
public static int square(int n) public static double square(double x) public static void greet(String name) public static int max(int a, int b)
| Call | Result | Why |
|---|---|---|
square(5) | 25 (an int) | the int argument matches square(int) |
square(2.5) | 6.25 (a double) | a double argument matches square(double) |
greet("Ada") | no value | void: use it as a statement only |
max(3, 9) | 9 | two int arguments, in order |
max(3) | does not compile | wrong number of arguments |
max(3, "9") | does not compile | a String where an int is required |
int r = greet("Ada"); | does not compile | void method used as a value |
Does the method change the caller's variable?
public static void addTen(int n) {
n = n + 10;
System.out.println("inside: " + n);
}
public static void main(String[] args) {
int score = 5;
addTen(score);
System.out.println("outside: " + score);
}
inside: 15 outside: 5
The parameter n was initialized with a copy of score's value, 5. The method changed its own copy to 15. The caller's score is a different variable and still holds 5.
Trace which line prints and in what order.
public static int twice(int x) {
System.out.println("in twice");
return x * 2;
// nothing after return runs
}
public static void main(String[] args) {
System.out.println("start");
int r = twice(4) + twice(1);
System.out.println("r = " + r);
}
start in twice in twice r = 10
main prints start, then evaluates twice(4) + twice(1) left to right. Each call interrupts main, prints in twice, returns a value, and control resumes where the call was. The sum is 8 + 2, so r is 10.
Which version runs for each call?
public static String describe(int n) {
return "int " + n;
}
public static String describe(double x) {
return "double " + x;
}
public static String describe(String s) {
return "String " + s;
}
public static void main(String[] args) {
System.out.println(describe(7));
System.out.println(describe(7.0));
System.out.println(describe("seven"));
}
int 7 double 7.0 String seven
All three share the name describe; their signatures describe(int), describe(double), and describe(String) differ in parameter type, so the arguments decide which runs.
Expect a method header and a list of calls, and you decide which call is legal, what it returns, and how it is used. Count arguments, check their order and types, and check whether the method is void. Questions about call by value present a method that modifies its parameter and ask what the caller's variable holds afterward (it is unchanged for a primitive argument). Overloading questions ask you to match arguments to signatures.
- What is the signature of
public static int clamp(int value, int low, int high)?Show answer
clamp(int, int, int): the name and the ordered list of parameter types. The return typeintand the parameter names are not part of the signature. - Which call is legal for
public static double half(int n)?A. half(); B. half(3, 4); C. double h = half(9); D. int h = half(9);
Show answer
C. A passes no argument and B passes two to a one-parameter method. D tries to store a
doubleresult in anintwithout a cast, which does not compile. - What is printed?
public static int triple(int n) { return n * 3; } public static void main(String[] args) { int a = 4; triple(a); System.out.println(a); a = triple(a); System.out.println(a); }Show answer
4and then12. The first call returns 12, but the value is discarded andais unchanged. The second call stores the returned value ina. - What is printed?
public static void change(int x) { x = 99; } public static void main(String[] args) { int y = 1; change(y); System.out.println(y); }Show answer
1. The parameterxreceived a copy ofy, so setting it to 99 has no effect ony. - Can a class contain
public static int size(String s)andpublic static double size(String s)together? Why or why not?Show answer
No. The signatures are both
size(String); the return type is not part of the signature, so these are not different overloads and the compiler rejects the second declaration. - Order the output of this code.
public static void show(String label) { System.out.println(label); } public static void main(String[] args) { show("A"); show("B"); show("A"); }Show answer
A,B,A. Each call runs the method body once, in the order the calls appear, and control returns to the line after each call.