AP® Computer Science A · Unit 1 · Topic 1.9

Reading a Method Signature

A method signature is the method's name plus its parameter types, and it tells you exactly what the method accepts and, together with the return type, what it hands back, all without reading a single line inside it.

A method call is a promise, and the signature is where that promise is written down. The return type tells you what kind of value you get back when the call finishes: a double, a boolean, a String, or void if nothing comes back. The name tells you what to call it. The parameter list tells you exactly what you must hand over to use it, in order, by type. None of these three jobs overlaps, which is exactly why you need all three to know what a method does from the outside.

Take public double average(int[] data, int n). Before reading the body you already know: pass it an int array and an int, in that order, and it will hand back a double. Whether it sums the whole array or just the first n elements is hidden inside, but the shape of the deal is fixed. This is the whole point of a signature: it lets you use a method correctly as a black box, which is exactly what happens every time you call a library method you never wrote.

Signatures also control overloading. When two methods share a name, Java decides which one runs by matching the types and number of arguments at the call site against each method's parameter list. That matching only looks at types and order, never at the names you gave the parameters, which is why two methods can look different on the page but still collide at compile time. This sets up everything later in the unit about calling methods on objects: once you can read a signature, you can predict what any method needs and returns before you ever see how it works inside.

Key terms

Method signature
A method's name together with the number, types, and order of its parameters.
Return type
The type of value a method sends back to the caller, or void if it sends nothing back.
Parameter list
The ordered set of types a method requires each time it is called.
Overloading
Giving several methods the same name but different parameter lists so Java can pick the right one by the arguments used.

Watch it explained

  1. How it worksHow do the return type, the name, and the parameter list each carry a different promise?
  2. Worked exampleFind what public double average(int[] data, int n) tells you before you read its body.
  3. How it worksHow does Java pick which overloaded method to run when two of them share a name?
  4. Common mistakeWhy isn't the parameter's name part of what makes two method signatures different?

Check yourself

Your turn1 of 2
Given the signature public double average(int[] data, int n), what can you tell before reading a single line of its body?

End of topic.