C Mps 161 Class Notes Chap 05
C Mps 161 Class Notes Chap 05
Methods
5.1 Introduction
method
public static int max(int num1, int num2) { int z = max(x, y);
header
int result;
method actual parameters
body parameter list (arguments)
if (num1 > num2)
result = num1;
else
result = num2;
return value
return result;
}
FIGURE 5.1 A method definition consists of a method header and a method body.
Declaring a method
System.out.println(max(3, 4));
• When a program calls a method, program control is transferred to the called method.
• A called method returns control to the caller when its return statement is executed or
when its method-ending closing brace is reached.
return result;
}
}
• The main method is just like any other method except that it is invoked by the Java
interpreter.
• The main method’s header is always the same, like the one in this example, with the
modifiers public and static, return value type void, method name main, and a
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
FIGURE 5.2 When the max method is invoked, the flow of control transfers to it. Once
the max method is finished, it returns control back to the caller.
i: 5 num1: 5
pass 2
parameters
j: 2 num2: 2
k: 5 result: 5
NOTE
One of the benefits of methods is for reuse. The max method can be invoked from any
class besides TestMax. If you create a new class Test, you can invoke the max method
using ClassName.methodName (i.e., TestMax.max).
• Each time a method is invoked, the system stores parameters and local 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.
• The variables defined in the main method are i, j, and k.
• The variables defined in the max method are num1, num2, and result.
• The variables num1, num2 are defined in the method signature and are parameters of
the method.
• Their values are passed through method invocation.
The main method The max method is The max method is The main method
is invoked. invoked. finished and the return is finished.
value is sent to k.
FIGURE 5.3 When the max method is invoked, the flow of control transfers to the max
method. Once the max method is finished, it returns control back to the caller.
• To see the difference between a void and a value-returning method, let us redesign
the printGrade method to return a value. The new method, which we call getGrade,
returns the grade.
• When calling a method, you need to provide arguments, which must be given in the
same order as their respective parameters in the method specification. This is known
as parameter order association.
• You can use nPrintln (“Hello”, 3) to print “Hello” 3 times.
CAUTION
• The arguments must match the parameters in order, number, and compatible type, as
defined in the method signature.
// Swapping n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("\t\tAfter swapping n1 is " + n1
+ " n2 is " + n2);
}
}
The main method The swap method The swap method The main method
is invoked is invoked is finished is finished
FIGURE 5.4 The values of the variables are passed to the parameters of the method.
• The arguments and parameters may have the same name, however, no change occurs
because the parameter is a local variable in the method with its own memory space.
The local variable is allocated when the method is invoked, and it disappears when
the method is returned to its caller.
• Methods can be used to reduce redundant coding and enable code reuse. Methods can
also be used to modularize code and improve the quality of the program.
import java.util.Scanner;
while (decimal != 0) {
int hexValue = decimal % 16;
hex = toHexChar(hexValue) + hex;
decimal = decimal / 16;
}
return hex;
}
• Both max (int, double) and max (double, int) are possible candidates to match
max(1, 2). Since neither of them is more specific than the other, the invocation is
ambiguous.
• You can declare a local variable with the same name multiple times in different non-
nesting blocks in a method, but you cannot declare a local variable twice in nested
blocks.
• A variable can be declared multiple times in non-nested blocks, but can be declared
only once in nesting blocks.
FIGURE 5.6 A variable can be declared multiple times in nonnested blocks but only once
in nested blocks.
• The last statement would cause a syntax error because variable i is not defined
outside of the for loop.
• The Math class contains the methods needed to perform basic mathematical
functions.
• Some useful methods in the Math class can be categorized as trigonometric methods,
exponent methods, and service methods.
• You can use two useful double constants, PI and E (base of natural logarithm)
• Each method has a single double parameter, and its return type is double.
Examples:
Math.sin(0) returns 0.0
Math.sin(Math.PI / 6) returns 0.5
Math.sin(Math.PI / 2) returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6) returns 0.866
Math.cos(Math.PI / 2) returns 0
Examples:
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns 22.91785
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
Examples:
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 3.0
Math.min(2.5, 3.6) returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1
• The random method generates a random double value greater than or equal to 0.0 or
less than 1.0 (0 <= Math.random( ) < 1.0).
Examples:
In general,
// Print random characters between '!' and '~', 25 chars per line
for (int i = 0; i < NUMBER_OF_CHARS; i++) {
char ch = RandomCharacter.getRandomLowerCaseLetter();
if ((i + 1) % CHARS_PER_LINE == 0)
System.out.println(ch);
else
System.out.print(ch);
}
}
}
Method Signature
Black Box
Method body
FIGURE 5.8 The method body can be thought of as a black box that contains the detailed
implementation for the method.