download

Matakuliah
Tahun
Versi
: M0074/PROGRAMMING II
: 2005
: 1/0
MATERI PENDUKUNG
METHOD
1
• Methods
• Allow programmers to modularize programs
– Makes program development more manageable
– Software reusability
– Avoid repeating code
• Local variables
– Declared in method declaration
• Parameters
– Communicates information between methods via method calls
• General format of method declaration:
– return-value-type method-name( parameter1, parameter2, …,
parameterN )
{
declarations and statements
}
2
• Method can also return values:
return expression;
• Method Overloading
– Several methods of the same name
– Different parameter set for each method
• Number of parameters
• Parameter types
– Example:
•
•
•
•
void print(int a);
void print(char c);
void print(int a, char c);
void print(char c, int a);
3
• Recursive method
– Calls itself (directly or indirectly) through
another method
– Method knows how to solve only a base case
– Method divides problem
• Base case
• Simpler problem
– Method now divides simpler problem until solvable
– Recursive call
– Recursive step
4
• Two ways to pass arguments to methods
– Pass-by-value
• Copy of argument’s value is passed to called method
• In Java, every primitive is pass-by-value
– Pass-by-reference
•
•
•
•
Caller gives called method direct access to caller’s data
Called method can manipulate this data
Improved performance over pass-by-value
In Java, every object is pass-by-reference
– In Java, arrays are objects
» Therefore, arrays are passed to methods by reference
5