$RXNXXEX
$RXNXXEX
PROGRAMMING I
Session 2A – Methods
Slide 2
Session Outline
The key topics to be covered in the session are as follows:
• Methods
• Defining Methods
• Parameter passing
• Overloading methods
• The scope of variables
Slide 3
Reading List
• Chapter 5 – Big Java Late Objects (Horstmann, 2012)
Slide 4
Topic One
METHODS
Slide 5
Introduction
• A method packages a computation consisting of multiple
steps into a form that can be easily understood and reused.
• A method is a sequence of instructions with a name.
• Every Java program has a method called main.
• You call a method in order to execute its instructions.
Slide 6
Introduction cont’d
• A method is a collection of statements grouped together to
perform an operation.
• In earlier slides we have used predefined methods such as
System.out.println, JOption-Pane.showMessageDialog,
JOptionPane.showInputDialog, Integer.parseInt,
Double.parseDouble, System.exit, Math.pow, and
Math.random.
• These methods are defined in the Java library.
Slide 7
Topic Two
DEFINING METHODS
Slide 8
Defining a Method - Syntax
• The syntax for defining a method is as follows:
Slide 9
Understanding the syntax
• The method syntax specifies the modifiers, return value
type, method name, and parameters of the method.
• The static modifier is used for all the methods for now.
• A method may return a value. The returnValueType is the
data type of the value the method returns.
• Some methods perform desired operations without
returning a value. In this case, the returnValueType is the
keyword void.
• For example, the returnValueType is void in the main
method, as well as in System.exit, System.out.println, and
JOptionPane.showMessageDialog.
Slide 10
Understanding the syntax cont’d
• If a method returns a value, it is called a value-returning
method, otherwise it is a void method.
• The variables defined in the method header are known as
formal parameters or simply parameters.
• A parameter is like a placeholder.
• When a method is invoked, you pass a value to the parameter.
• This value is referred to as an actual parameter or argument.
The parameter list refers to the type, order, and number of the
parameters of a method.
Slide 11
Understanding the syntax cont’d
• The method name and the parameter list together constitute
the method signature.
• Parameters are optional; that is, a method may contain no
parameters. For example, the Math.random() method has no
parameters.
• In order for a value-returning method to return a result, a
return statement using the keyword return is required.
• The method terminates when a return statement is executed.
• In the method header, you need to declare a separate data
type for each parameter.
Slide 12
Implementing Methods
Slide 13
Calling a Method
• In creating a method, you define what the method is to do. To use
a method, you have to call or invoke it.
• There are two ways to call a method, depending on whether the
method returns a value or not.
• If the 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).
Slide 14
Sample program using Method
public class TestMax {
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
public static void main(String[] args) {
int i = 5, j = 2, k = max(i, j) ;
System.out.println("The maximum between " + i + " and " + j + " is " + k);
}
}
Slide 15
Call Stacks
• Each time a method is invoked, the system stores
parameters and variables in an area of memory known as a
stack, which stores elements in last-in, first-out fashion.
• When a method calls another method, the caller’s stack
space is kept intact, and new space is created to handle the
new method call.
• When a method finishes its work and returns to its caller,
its associated space is released.
Slide 16
void Method
• Sometimes, you need to carry out a sequence of
instructions that does not yield a value.
• If that instruction sequence occurs multiple times, you will
want to package it into a method.
• In Java, you use the return type void to indicate the
absence of a return value.
• A void method returns no value, but it can produce output.
Slide 17
void Method Example
public class TestReturnGradeMethod {
public static void main(String[] args) {
System.out.print("The grade is "+ printGrade(78.5) );
System.out.print("\nThe grade is "+ printGrade(59.5) );
}
public static void printGrade(double score) {
if (score >= 90.0) System.out.println('A');
else if (score >= 80.0) System.out.println('B');
else if (score >= 70.0) System.out.println('C');
else if (score >= 60.0) System.out.println('D');
else System.out.println('F');
}
} Slide 18
Topic Three
PARAMETER PASSING
Slide 19
Parameter passing
• When a method is called, variables are created for receiving
the method’s arguments.
• These variables are called parameter variables. (Another
commonly used term is formal parameters.)
• The values that are supplied to the method when it is
called are the arguments of the call.
• Each parameter variable is initialized with the
corresponding argument.
Slide 20
Passing Parameters by Values
• The power of a method is its ability to work with parameters.
• 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.
• When you invoke a method with a parameter, the value of
the argument is passed to the parameter.
• This is referred to as pass-by-value.
• If the argument is a variable rather than a literal value, the
value of the variable is passed to the parameter.
• The variable is not affected, regardless of the changes made
to the parameter inside the method.
Slide 21
Passing-by-value example
public class Increment {
public static void main(String[] args) {
int x = 1;
System.out.println("Before the call, x is " + x);
increment(x);
System.out.println("after the call, x is " + x);
}
public static void increment(int n) {
n++;
System.out.println("n inside the method is " + n);
}
}
Slide 22
Program Output
• The previous program produces the following output:
Slide 23
Topic Four
OVERLOADING METHODS
Slide 24
Overloading Methods
• The max method that was used earlier works only with the
int data type.
• But what if we need to determine which of two floating-
point numbers has the maximum value?
• The solution is to create another method with the same
name but different parameters.
• The concept where methods having the same name but
different parameters is known as method overloading.
• You cannot overload methods based on different modifiers
or return types.
Slide 25
Example: Overloading Methods
public class TestMethodOverloading {
public static void main(String[] args) {
// Invoke the max method with int parameters
System.out.println("The maximum between 3 and 4 is “ + max(3,
4) );
// Invoke the max method with the double parameters
System.out.println("The maximum between 3.0 and 5.4 is “ +
max(3.0, 4.5));
// Invoke the max method with three double parameters
System.out.println("The maximum between 3.0, 5.4, and 10.14 is " +
max(3.0, 5.4, 10.14) );
}
Dr. Jamal-Deen Abdulai, CSCD Slide 26
Example: Overloading Methods cont’d
/** Return the max between two int values */
public static int max(int num1, int num2) {
if (num1 > num2) return num1;
else return num2;
}
/** Find the max between two double values */
public static double max(double num1, double num2) {
if (num1 > num2) return num1;
else return num2;
}
/** Return the max among three double values */
public static double max(double num1, double num2, double num3){
return max(max(num1, num2), num3);
}
}
Slide 27
Understanding the code
• When calling max(3, 4) , the max method for finding the
maximum of two integers is invoked.
• When calling max(3.0, 5.4) , the max method for finding the
maximum of two doubles is invoked.
• When calling max(3.0, 5.4, 10.14), the max method for finding
the maximum of three double values is invoked.
• Both max(double, double) and max(int, int) are possible matches
for max(3, 4).
• The Java compiler finds the most specific method for a method
invocation.
• Since the method max(int, int) is more specific than max(double,
double), max(int, int) is used to invoke max(3, 4).
Slide 28
Topic Five
Slide 29
The scope of variables
• The scope of a variable is the part of the program where
the variable can be referenced.
• A variable defined inside a method is referred to as a local
variable.
• The scope of a local variable starts from its declaration and
continues to the end of the block that contains the variable.
• A local variable must be declared and assigned a value
before it can be used.
Slide 30
The scope of variables cont’d
• A parameter is actually a local variable. The scope of a
method parameter covers the entire method.
• A variable declared in the initial-action part of a for-loop
header has its scope in the entire loop.
• But a variable declared inside a for-loop body has its scope
limited in the loop body from its declaration to the end of
the block that contains the variable.
• Do not declare a variable inside a block and then attempt to
use it outside the block. It will result in an error.
Slide 31
The scope of variables cont’d
• Do not declare a variable inside a block and then attempt to
use it outside the block. It will result in an error. See below:
for (int i = 0; i < 10; i++) {
}
System.out.println(i);
• The last statement would cause a syntax error, because
variable i is not defined outside of the for loop.
Slide 32
Method Abstraction and Stepwise
Refinement
• The key to developing software is to apply the concept of abstraction.
• Method abstraction is achieved by separating the use of a method
from its implementation.
• The client can use a method without knowing how it is implemented.
• The details of the implementation are encapsulated in the method
and hidden from the client who invokes the method. This is known as
information hiding or encapsulation.
• If the programmer decide to change the implementation, the client
program will not be affected, provided the method signature remains
unchanged.
• The implementation of the method is hidden from the client in a
“black box”.
Slide 33
Divide-and-Conquer
• The concept of method abstraction can be applied to the
process of developing programs.
• When writing a large program, you can use the divide-and-
conquer strategy, also known as stepwise refinement, to
decompose it into subproblems.
• The subproblems can be further decomposed into smaller,
more manageable problems.
Slide 34
References
• Big Java Late Objects (Horstmann, 2012)
• An Introduction to Problem Solving and Programming
(Savitch, 2012)
• Introduction to Java Programming(Liang, 2011)
Slide 35