0% found this document useful (0 votes)
9 views

C Mps 161 Class Notes Chap 05

Uploaded by

Avinash R Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

C Mps 161 Class Notes Chap 05

Uploaded by

Avinash R Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter 5

Methods

5.1 Introduction

• A method is a collection of statements that are grouped together to perform an


operation.
• You will learn how to:
o create your own mthods with or without return values,
o invoke a method with or without parameters,
o overload methods using the same names, and
o apply method abstraction in the program design.

5.2 Defining a Method

• In general, a method has the following syntax:

Modifier returnValueType methodName(list of parameters) {


// method body;
}

• A method declaration consists of a method header and a method body.


• The following method finds which of two integers is bigger. The method named max,
has two int parameters, num1 and num2, the larger of which is returned by the
method.
Define a method Invoke a method

modifier return value type method name formal parameters

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.

CMPS161 Class Notes (Chap 05) Page 1 /20 Kuo-pao Yang


• The method header specifies the modifiers, return value type, method name, and
parameters of the method.
• The modifier, which is optional, tells the compiler how to call the method.
• The static modifier is used for all the methods in this chapter.
• A method may return a value. The returnValueType is the data type of the value the
method returns.
• If the method doesn’t return a value, the returnValueType is the keyword void. For
example, returnValueType in the main method is void as well as System.out.println.
• The parameter list refers to the type, order, and number of the parameters of a
method. The method name and the parameter list together constitute the method
signature. Parameters are optional; a method may contain no parameters.
• The variables defined in the method header are knows as formal parameters.
• When a method is invoked, you pass a value to the parameter. This value is referred
to as actual parameter or argument.
• The method body contains a collection of statements that define what the method
does.
• A return statement using the keyword return is required for a non-void method to
return a result.
• The method terminates when a return statement is executed.

Declaring a method

public static int max(int num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}

CMPS161 Class Notes (Chap 05) Page 2 /20 Kuo-pao Yang


5.3 Calling a Method

• To use a method, you have to call or invoke it.


• There are two ways to call a method; the choice is based 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.

int larger = max(3, 4);

System.out.println(max(3, 4));

• If the method returns void, a call to the method must be a statement.


System.out.println(“Welcome to Java!“);

• 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.

LISTING 5.1 TestMax.java (Page 158)


// TestMax.java: demonstrate using the max method
public class TestMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i +
" and " + j + " is " + k);
}

/** 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;
}
}

The maximum between 5 and 2 is 5

• 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

CMPS161 Class Notes (Chap 05) Page 3 /20 Kuo-pao Yang


parameter of the string[ ] type. String [ ] indicates that the parameter is an array of
String.
• The statements in main may invoke other methods that are defined in the class that
contains the main method or in other classes.
• The main method invokes max [i, j], which is defined in the same class with the main
method.
• When the max method is invoked, variable i’s value 5 is passed to num1, and variable
j’s value 2 is passed to num2 in the max method.
• The flow of control transfers to the max method. The max method is executed.
• When the return statement in the max method is executed, the max method returns the
control to its caller.
pass the value of i
pass the value of j

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.

• 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 and num2 are defined in the method signature and are parameters
of the method. There methods are passed through method invocation.

The main method pass 5 The max method

i: 5 num1: 5
pass 2
parameters

j: 2 num2: 2

k: 5 result: 5

CMPS161 Class Notes (Chap 05) Page 4 /20 Kuo-pao Yang


CAUTION

• A return statement is required for a non-void method. The following method is


logically correct, but it has a compilation error, because the Java compiler thinks it
possible that this method does not return any value.

public static int sign(int n) {


if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
}

• To fix this problem, delete if (n < 0) in the code.

public static int sign(int n) {


if (n > 0) return 1;
else if (n == 0) return 0;
else return –1;
}

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).

CMPS161 Class Notes (Chap 05) Page 5 /20 Kuo-pao Yang


5.3.1 Call Stacks

• 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.

Space required for the


max method
result: 5
num2: 2
num1: 5
Space required for the Space required for the Space required for the
main method main method main method
k: k: k: 5 Stack is empty
j: 2 j: 2 j: 2
i: 5 i: 5 i: 5

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.

CMPS161 Class Notes (Chap 05) Page 6 /20 Kuo-pao Yang


5.4 void Method Example

• This section shows how to declare and invoke a void method.

LISTING 5.2 TestVoidMethod.java (Page 160)


public class TestVoidMethod {
public static void main(String[] args) {
System.out.print("The grade is ");
printGrade(78.5);

System.out.print("The 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');
} The grade is C
} The grade is F
}

• 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.

LISTING 5.3 TestReturnGradeMethod.java (Page 161)


public class TestReturnGradeMethod {
public static void main(String[] args) {
System.out.print("The grade is " + getGrade(78.5));
System.out.print("\nThe grade is " + getGrade(59.5));
}

public static char getGrade(double score) {


if (score >= 90.0)
return 'A';
else if (score >= 80.0)
return 'B';
else if (score >= 70.0)
return 'C';
else if (score >= 60.0)
return 'D';
else The grade is C
return 'F'; The grade is F
}
}

CMPS161 Class Notes (Chap 05) Page 7 /20 Kuo-pao Yang


5.5 Passing Parameters by 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 specification. This is known
as parameter order association.
• You can use nPrintln (“Hello”, 3) to print “Hello” 3 times.

public static void nPrintln(String message, int n) {


for (int i = 0; i < n; i++)
System.out.println(message);
}

CAUTION
• The arguments must match the parameters in order, number, and compatible type, as
defined in the method signature.

LISTING 5.5 Pass by Value (Page 163)


• 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, 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.
// TestPassByValue.java: Demonstrate passing values to methods
public class TestPassByValue {
/** Main method */
public static void main(String[] args) {
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " +
num1 + " and num2 is " + num2);
// Invoke the swap method to attempt to swap two variables
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " +
num1 + " and num2 is " + num2);
}

/** Swap two variables */


public static void swap(int n1, int n2) {
System.out.println("\tInside the swap method");
System.out.println("\t\tBefore swapping n1 is " + n1
+ " n2 is " + n2);

// Swapping n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("\t\tAfter swapping n1 is " + n1
+ " n2 is " + n2);
}
}

CMPS161 Class Notes (Chap 05) Page 8 /20 Kuo-pao Yang


• Before the swap method is invoked, num1 is 1 and num2 is 2. After the swap method
is invoked, num1 continues to be 1 and num2 continues to be 2.
• Their values are not swapped when the swap method is invoked.
• The values of the arguments num1 and num2 are passed to n1 and n2, but n1 and n2
have their own memory locations independent of num1 and num2.
• Therefore, changes to n1 and n2 do not affect the contents of num1 and num2.

The values of num1 and num2 are


passed to n1 and n2. Executing swap
does not affect num1 and num2.

Space required for the


swap method
temp:
n2: 2
n1: 1
Space required for the Space required for the Space required for the
main method main method main method Stack is empty
num2: 2 num2: 2 num2: 2
num1: 1 num1: 1 num1: 1

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.

CMPS161 Class Notes (Chap 05) Page 9 /20 Kuo-pao Yang


5.6 Modularizing Code

• 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.

LISTING 5.6 GreatestCommonDivisorMethod.java (Page 165)


• It prompts the user to enter two integers and displays their greatest common divisor.

import java.util.Scanner;

public class GreatestCommonDivisorMethod {


/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);

// Prompt the user to enter two integers


System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();

System.out.println("The greatest common divisor for " + n1 +


" and " + n2 + " is " + gcd(n1, n2));
}

/** Return the gcd of two integers */


public static int gcd(int n1, int n2) {
int gcd = 1; // Initial gcd is 1
int k = 1; // Possible gcd

while (k <= n1 && k <= n2) {


if (n1 % k == 0 && n2 % k == 0)
gcd = k; // Update gcd
k++;
}

return gcd; // Return gcd


}
}

Enter first integer: 125


Enter second integer: 2525
The greatest common divisor for 125 and 2525 is 25

CMPS161 Class Notes (Chap 05) Page 10 /20 Kuo-pao Yang


5.7 Problem: Coverting Decimals to hexadecimals

7F in Hexadecimal 7 X 161 + 15 X 160 = 127 in Decimal

FFFF in Hexadecimal 15 X 163 + 15 X 162 +15 X 161 + 15 X 160 = 65535 in Decimal

431 in Hexadecimal 4 X 162 + 3 X 161 + 1 X 160 = 1073 in Decimal

123 in Decimal is 7B in Hexadecimal

LISTING 5.7 Decimal2HexCoversion.java (Page 167)


import java.util.Scanner;

public class Decimal2HexConversion {


/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);

// Prompt the user to enter a decimal integer


System.out.print("Enter a decimal number: ");
int decimal = input.nextInt();

System.out.println("The hex number for decimal " +


decimal + " is " + decimalToHex(decimal));
}

/** Convert a decimal to a hex as a string */


public static String decimalToHex(int decimal) {
String hex = "";

while (decimal != 0) {
int hexValue = decimal % 16;
hex = toHexChar(hexValue) + hex;
decimal = decimal / 16;
}

return hex;
}

/** Convert an integer to a single hex digit in a character */


public static char toHexChar(int hexValue) {
if (hexValue <= 9 && hexValue >= 0)
return (char)(hexValue + '0');
else // hexValue <= 15 && hexValue >= 10
return (char)(hexValue - 10 + 'A');
}
}

Enter a decimal number: 123


The hex number for decimal 123 is 7B

CMPS161 Class Notes (Chap 05) Page 11 /20 Kuo-pao Yang


5.8 Overloading Methods
public static double max(double num1, double num2) {

if (num1 > num2)


return num1;
else
return num2;
}
• If you need to find which of two floating-point numbers has the maximum value, the
code above shows you just that. If you call max with int parameters, the max method
that expects int parameters will be invoked. If you call max with double parameters,
the max method that expects double parameters will be invoked.
• This is referred to as method overloading; that is, two methods have the same name
but different parameters lists.
• The Java compiler determines which method is used based on the method signature.

LISTING 5.9 TestMethodOverloading.java (Page 165)


// TestMethodOverloading.java: Demonstrate method overloading
public class TestMethodOverloading {
/** Main method */
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, 5.4));

// 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));
}

/** 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);
}
}

CMPS161 Class Notes (Chap 05) Page 12 /20 Kuo-pao Yang


• The program invokes three different max methods that will have the same name:
max(3, 4), max(3.0, 5.4), and max(3.0, 5.4, 10.14).
• When calling max(3, 4), The max method for finding maximum integers is invoked.
• When calling max(3.0, 5.4), The max method for finding maximum doubles is
invoked.
• When calling max(3.0, 5.4, 10.14), The max method for finding maximum of three
double values is invoked.
• 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).
• Overloading methods can make programs clearer and more readable. Methods that
perform closely related tasks should be given the same name.
• Overloaded methods must have different parameter lists. You can’t overload
methods based on different modifiers or return types.

NOTE: Ambiguous Invocation


• Sometimes there may be two or more possible matches for an invocation of a method,
but the compiler cannot determine the most specific match. This is referred to as
ambiguous invocation. Ambiguous invocation is a compilation error.

public class AmbiguousOverloading {


public static void main(String[] args) {
System.out.println(max(1, 2));
}

public static double max(int num1, double num2) {


if (num1 > num2)
return num1;
else
return num2;
}

public static double max(double num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}
}

• 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.

CMPS161 Class Notes (Chap 05) Page 13 /20 Kuo-pao Yang


5.9 The Scope of Variables

• A local variable: a variable defined inside a method.


• Scope of a variable is the part of the program where the variable can be referenced.
• 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 before it can be used.
• 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 and to the end of the block that contains the variable.

public static void method1() {


.
.
for (int i = 1; i < 10; i++) {
.
The scope of i .
int j;
.
The scope of j .
.
}
}

• 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.

It is fine to declare i in two It is wrong to declare i in


non-nesting blocks two nesting blocks

public static void method1() { public static void method2() {


int x = 1;
int y = 1; int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i; for (int i = 1; i < 10; i++)
} sum += i;
}
for (int i = 1; i < 10; i++) {
y += i; }
}
}

FIGURE 5.6 A variable can be declared multiple times in nonnested blocks but only once
in nested blocks.

CMPS161 Class Notes (Chap 05) Page 14 /20 Kuo-pao Yang


Caution
• Do not declare a variable inside a block and then use it outside the block.

for (int i = 0; i < 10; i++) {


...
}

System.out.println(i); // a common mistake

• The last statement would cause a syntax error because variable i is not defined
outside of the for loop.

CMPS161 Class Notes (Chap 05) Page 15 /20 Kuo-pao Yang


5.10 The Math Class

• 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)

5.10.1 Trigonometric methods:


sin(double a)
cos(double a)
tan(double a)
acos(double a)
asin(double a)
atan(double a)

• 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

5.10.2 Exponent Methods


• There are four methods related to exponents in the math class:

exp(double a) // Returns e raised to the power of a.


log(double a) // Returns the natural logarithm of a.
pow(double a, double b) // Returns a raised to the power of b.
sqrt(double a) // Returns the square root of a.

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

CMPS161 Class Notes (Chap 05) Page 16 /20 Kuo-pao Yang


5.10.3 The Rounding Method
• There are five methods related to rounding in the math class:

double ceil(double x) // rounded up to its nearest integer.


// This integer is returned as a double value.
double floor(double x) // is rounded down to its nearest integer.
// This integer is returned as a double value.
double rint(double x) // is rounded to its nearest integer.

// If x is equally close to two integers, the even one is returned as a double.

int round(float x) // Return (int)Math.floor(x+0.5).


long round(double x) // Return (long)Math.floor(x+0.5).

Math.ceil(2.1) returns 3.0


Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3

5.10.4 The min, max, and abs Methods


• The min and max are overloaded to return the minimum and maximum numbers
between two numbers.
• The abs is overloaded to return the absolute value of the number.

max(a, b)and min(a, b) // Returns the maximum or minimum of two parameters.


abs(a) // Returns the absolute value of the parameter.

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

CMPS161 Class Notes (Chap 05) Page 17 /20 Kuo-pao Yang


5.10.5 The random Methods

• 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).

random() // Returns a random double value in the range [0.0, 1.0).

Examples:

Returns a random integer


(int)(Math.random() * 10)
between 0 and 9.

50 + (int)(Math.random() * 50) Returns a random integer


between 50 and 99.

In general,

a + Math.random() * b Returns a random number between


a and a + b, excluding a + b.

CMPS161 Class Notes (Chap 05) Page 18 /20 Kuo-pao Yang


5.11 Case Study: Generating Random Characters

public class RandomCharacter {


/** Generate a random character between ch1 and ch2 */
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}

/** Generate a random lowercase letter */


public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}

/** Generate a random uppercase letter */


public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}

/** Generate a random digit character */


public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}

/** Generate a random character */


public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}
}

public class TestRandomCharacter {


/** Main method */
public static void main(String args[]) {
final int NUMBER_OF_CHARS = 175;
final int CHARS_PER_LINE = 25;

// 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);
}
}
}

CMPS161 Class Notes (Chap 05) Page 19 /20 Kuo-pao Yang


5.12 Method Abstraction and Stepwise Refinement

• 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 you decide to change the implementation, the client program will not be affected,
provided that you don’t change the method signature.
• The implementation of the method is hidden in a black box from the client.

Optional arguments Optional return


for Input value

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.

CMPS161 Class Notes (Chap 05) Page 20 /20 Kuo-pao Yang

You might also like