Methods
Methods
-
A method is like a machine
-
Zero or more inputs
-
Zero or one output
-
Other names:
-
Function
-
Procedure
-
Applications
-
Scientists use mathematical functions to calculate formulas.
-
Programmers use functions to build modular programs.
Example
Example
Example
Example
Example
Example
Example
Flow of control
(2)
(3)
flow of control
-
What happens when a function is called:
-
Control transfers to the function code.
-
Argument variables are assigned the values given in the call.
-
Function code is executed.
-
Return value is assigned in place of the function
name in calling code.
-
Control transfers back to the calling code. This is known as "pass by value”.
Scope
-
Scope (of a variable):
-
The code that can refer to that variable.
-
Example
Memory management in stack
- What happens in memory when we call functions?
-
What happens in memory when we define variables?
Don't forget static
Can't make static reference to method
returnType methodName(…) in class YourClass.
static int min(int a, int b) { if (a < b) return a; else if (b < a) return b; System.out.println("they are equal!!!"); return a; }
Control returns immediately from a method when a return is executed.
DUE SOOn
- Quiz Wednesday
- Lab 3 due Thursday at 10pm
- zybooks Chapter 7 due Friday at noon
- Program 2 (in zybooks - 3 parts) due Friday at 10pm
Copy of Methods
By Narges Norouzi
Copy of Methods
- 135