Method Signatures
Big idea: A method is a named block of code you can call. Its signature (name plus parameter types) tells you exactly how to call it.
- Identify the correct method to call based on documentation and method signatures.
- Describe how to call methods.
Parts of a method header
A parameter is a variable in the header that receives a value. An argument is the value you pass when you call the method. The signature is the method name plus the ordered list of parameter types; the return type is not part of it.
public static double average(int a, int b)
// ^return ^name ^parameters
// signature: average(int, int)Calling a method
Arguments must match the parameters in number, order, and type. Java uses call by value: each parameter gets a copy of its argument. When a method is called, the caller pauses, the method runs, and then control returns to just after the call.
A void method returns nothing, so you call it as a statement. A non-void method returns a value that you should store, print, or use in an expression.
static int area(int w, int h) { return w * h; }
static void greet(String name) { System.out.println("Hi, " + name); }Using themSystem.out.println(area(3, 4));
int a = area(2, 5);
greet("Sam");
System.out.println(a);Output12 Hi, Sam 10
Overloading
Overloaded methods share a name but have different signatures. Java picks the one whose parameter types match the arguments.
Methodsstatic int max(int a, int b) {
if (a > b) return a;
return b;
}
static double max(double a, double b) {
if (a > b) return a;
return b;
}
static int max(int a, int b, int c) {
return max(max(a, b), c);
}Using themSystem.out.println(max(3, 9));
System.out.println(max(2.5, 1.0));
System.out.println(max(4, 1, 7));Output9 2.5 7
- Signature = method name + ordered parameter types.
- Arguments must match parameters in number, order, and type. Parameters receive copies (call by value).
voidmethods return nothing; non-void return values should be used.- Overloaded methods have the same name and different parameter lists.
- Procedural abstraction: you can use a method knowing what it does, not how.
- Return type is not part of the signature. Two methods that differ only in return type won't compile.
- Parameter names don't matter for the signature, only types and order.