Introduction to Programming
Week – 7
Method
LEARNING OUTCOMES
• LO3: Design and apply the right algorithms to solve problem Using
JAVA
OUTLINE
Defining a Method
Calling a method
Passing argument by value
Overloading method
The scope of variable
Defining a Method
Defining a Method
• A method definition consists of method name, parameters, return
value type, and body. The syntax for defining a method is as follows:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
Calling a method
Calling a method
• To execute the method, you have to call or invoke it. The program that calls
the function is called a caller.
• If a method returns a value, a call to the method is usually treated as a
value. For example, int larger = max(3, 4); calls max(3, 4) and assigns the
result of the method to the variable larger.
• Another example of a call that is treated as a value is
System.out.println(max(3, 4)); which prints the return value of the method
call max(3, 4).
• If a method returns void, a call to the method must be a statement. For
example, the method println returns void. The following call is a statement:
System.out.println("Welcome to Java!")
Passing argument by value
Passing argument by value
• The power of a method is its ability to work with parameters. You can
use println to print any string, and max to find the maximum of any
two int values. When calling a method, you need to provide
arguments, which must be given in the same order as their respective
parameters in the method signature.
Example
Overloading method
Overloading Method
• The max method used earlier works only with the int data type. But
what if you need to determine which of the two floating-point
numbers has the maximum value? The solution is to create another
method with the same name but different parameters,
The scope of variable
The scope of variable
• You can declare a local variable with the same name in different
blocks in a method, but you cannot declare a local variable twice in
the same block or in nested blocks, as shown in Figure below
REFERENCES
• Y.Daniel, 2020, Introduction to Java Programming and Data Structure,
Comprehensive Edition, Chapter 6