E N D
Chapter 5 Methods Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a program and reuse it by many other programs. For example, often you need to find the maximum between two numbers. Whenever you need this function, you would have to write the following code: int result; if (num1 > num2) result = num1; else result = num2; If you define this function for finding a maximum number between any two numbers in a method, you don’t have to repeatedly write the same code. You need to define it just once and reuse it by any other programs. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Objectives • To define methods, invoke methods, and pass arguments to a method (§5.2-5.5). • To develop reusable code that is modular, easy-to-read, easy-to-debug, and easy-to-maintain. (§5.6). • To use method overloading and understand ambiguous overloading (§5.7). • To design and implement overloaded methods (§5.8). • To determine the scope of variables (§5.9). • To know how to use the methods in the Math class (§§5.10-5.11). • To learn the concept of method abstraction (§5.12). • To design and implement methods using stepwise refinement (§5.12). Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Defining Methods A method is a collection of statements that are grouped together to perform an operation. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Method Signature Method signature is the combination of the method name and the parameter list. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Formal Parameters The variables defined in the method header are known as formal parameters. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Actual Parameters and Formal Parameters • Location of actual parameter or argument to formal parameter is important. • Number of actual parameters must equal number of formal parameters. • Type of actual parameter must match type of formal parameter. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Return Value Type A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Example Return Value Types • Return type int • public static int max(int a, int b) { • Returns type integer • public static double max(int a, int b) { • Returns type double • public static void printn(String c) { • Does not return a value, so no return statement in this method. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Method body The method body is the code executed to produce the results. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Modifiers • Identifies how the method is used: • public: any other program has access to this method • static: static methods can be called without creating an instance of the class Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Modifiers • Java modifiers • public: all methods have access to the method • protected: only methods in the same package have access to the method • private: only methods in the same class has access to the method • Java structure • Package: contains one or more classes • Class: contains one or more methods • Subclass: derived from a class Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Calling Methods Listing 5.1 Testing the max method This program demonstrates calling a method max to return the largest of the int values Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
TestMax 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; } } Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation 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; } Calling Methods, cont. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation i is now 5 i 5 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation j is now 2 i j 5 2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation invoke max(i, j) i j 5 2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2 i j 5 2 num1 num2 5 2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation declare variable result i j 5 2 num1 num2 result 5 2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation (num1 > num2) is true since num1 is 5 and num2 is 2 i j 5 2 num1 num2 result 5 2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation result is now 5 i j 5 2 num1 num2 result 5 2 5 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation return result, which is 5 i j 5 2 num1 num2 result 5 2 5 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation return max(i, j) and assign the return value to k i j k 5 2 5 num1 num2 result 5 2 5 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Method Invocation Execute the print statement i j k 5 2 5 num1, num2, and result no longer exist Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
CAUTION A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value. To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Reuse Methods from Other Classes 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 (e.g., TestMax.max). publicclass Test { publicstaticvoid main(String[] args) { int a = 4; int b = 8; int c = TestMax.max(a,b); System.out.println("The largest of " + a + " and " + b + " is " + c); } } Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Call Stacks Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack i is declared and initialized Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack j is declared and initialized Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack Declare k Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack Invoke max(i, j) Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack pass the values of i and j to num1 and num2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack pass the values of i and j to num1 and num2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack (num1 > num2) is true Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack Assign num1 to result Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack Return result and assign it to k Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
animation Trace Call Stack Execute print statement Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
void Method Example This type of method does not return a value. The method performs some actions. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
TestVoidMethod public class TestVoidMethod { public static void main(String[] args) { System.out.print("The grade is "); printGrade(78.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'); } } } Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Passing Parameters public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using nPrintln(“Welcome to Java”, 5); What is the output? Suppose you invoke the method using nPrintln(“Computer Science”, 15); What is the output? Welcome to Java Welcome to Java Welcome to Java Welcome to Java Welcome to Java Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Pass by Value • Pass the value of the variable, not the memory location • Make changes to value will not change the value in the original variable • Listing 5.2 Testing Pass by value • This program demonstrates passing values to the methods. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
TestPassByValue 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); // Swap n1 with n2 int temp = n1; n1 = n2; n2 = temp; System.out.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2); } } Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Pass by Value, cont. After the swap, n2 = 1 and n1 = 2 But the values in num1 and num2 do not change Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
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. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
GreatestCommonDivisorMethod 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)); } Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
GreatestCommonDivisorMethod (cont.) /** 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 } } Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
PrimeNumberMethod public class PrimeNumberMethod { public static void main(String[] args) { final int NUMBER_OF_PRIMES = 50; // Number of primes to display final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line int count = 0; // Count the number of prime numbers int number = 2; // A number to be tested for primeness System.out.println("The first 50 prime numbers are \n"); // Repeatedly find prime numbers Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
PrimeNumberMethod (cont) while (count < NUMBER_OF_PRIMES) { // Print the prime number and increase the count if (isPrime(number)) { count++; // Increase the count if (count % NUMBER_OF_PRIMES_PER_LINE == 0) { // Print the number and advance to the new line System.out.printf("%-5s\n", number); } else System.out.printf("%-5s", number); } // Check if the next number is prime number++; number++; } } /** Check whether number is prime */ Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671