Method Signatures
AP Computer Science A
Understanding how methods work and how to call them
What is a Method?
Definition:
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.
Key Concepts:
- Named block of code: Methods have specific names to identify them
- Only runs when called: Methods don't execute automatically
- Enclosed in braces: Method body is contained within { }
- Procedural abstraction: You can use a method without knowing how it's written
Method Parameters
Parameter:
A variable declared in the header of a method or constructor that can be used inside the body of the method.
Purpose:
Parameters allow values (arguments) to be passed and used by a method or constructor.
In the examples above: name, a, and b are parameters.
Method Signatures
Method Signature:
For methods with parameters: method name + ordered list of parameter types
For methods without parameters: method name + empty parameter list
Examples:
Void vs Non-Void Methods
| Void Methods | Non-Void Methods |
|---|---|
| Do not have a return value | Return a value of a specific type |
| Not called as part of an expression | Must store return value or use in expression |
| Used for actions/operations | Used for calculations/data retrieval |
How to Call Methods
Void Method Calls:
Non-Void Method Calls:
Arguments vs Parameters
Argument:
A value that is passed into a method when the method is called.
Important Rules:
- Arguments must be compatible in number and order with parameter types
- Arguments are passed using call by value
- Call by value initializes parameters with copies of the arguments
Call by Value
Call by Value:
When calling methods, arguments are passed using call by value. This initializes the parameters with copies of the arguments.
Method Overloading
Method Overloading:
Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
Each method has a different signature based on its parameter list.
Method Call Flow of Control
A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing.
Flow: Step 1 -> Step 2 -> Step 3
Once the last statement in the method is executed or a return statement is executed, control returns to the point immediately following where the method was called.
Common Method Examples
Key Takeaways
Remember These Concepts:
- Method Signature: Name + parameter types (order matters!)
- Void methods: Perform actions, no return value
- Non-void methods: Return values that must be used
- Parameters vs Arguments: Parameters in definition, arguments in calls
- Call by Value: Methods work with copies of arguments
- Method Overloading: Same name, different signatures
- Flow of Control: Execution jumps to method, then returns