Chapter 5 Methods Benefits of Methods Write a method once and reuse it anywhere. Information hiding: hide the implementation from the user Reduce complexity 1 4 Motivating Example Often we need to find the maximum between two numbers A method is a construct for grouping statements together to perform a function. A method is defined and implemented once but can be used repeatedly A method can be used as a blackbox Defining and Using Methods Define a method give a definition of what the method is to do modifier returntype methodname(list of parameters) { collection of statements; Call or invoke a method use a method methodname(list of parameters) 5 Method Abstraction Method abstraction a black box that contains the detailed implementation for the method. Return Value Type A method may return a value (int, double, char, String, ) value-returning method A method may perform desired operations without returning a value (void) void method 3 6
Method Signature Method signature The combination of the method name and the parameter list main method The main method is a method that s invoked by JVM The main method s header is always the same //method body The statements in main method may invoke other methods that are defined in the class or in other classes Hello World! ); int number = (int) (Math.random()*100); 7 Parameters The variables defined in the method header are known as formal parameters When invoking a method, a value is passed to the parameter and this value is referred to as actual parameter or argument. The arguments must match the parameters in order, number, and compatible type Parameters are optional Example A program that defines and uses a method max to return the larger of the two int values TestMax.java 8 11 Method Body The method body contains a collection of statements A return statement is required for a value-returning method Calling Methods pass the value of i pass the value of j 9 12
i is now 5 invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2 13 16 j is now 2 declare variable result 14 17 invoke max(i, j) (num1 > num2) is true since num1 is 5 and num2 is 2 15 18
result is now 5 Execute the print statement 19 22 return result, which is 5 Call Stacks Each time a method is invoked, the system stores parameters and variables in an area of memory, known as a stack When a method calls another method, the caller's stack space is kept intact New space is created to handle the new method call When a method finishes, its associated space is released. 20 23 return max(i, j) and assign the return value to k i is declared and initialized 21 24
j is declared and initialized pass the values of i and j to num1 and num2 25 28 Declare k pass the values of i and j to num1 and num2 26 29 Invoke max(i, j) (num1 > num2) is true 27 30
31 Assign num1 to result CAUTION A return statement is required for a value-returning method Compiler error when it is possible that a method does not return a value public static int sign(int x) { if (x < 0) { return -1; public static int sign(int x) { if (x < 0) { return -1; { return 1; 34 Return result and assign it to k Reuse Methods from Other Classes A method can be invoked from other classes Invoking a static method defined in other classes ClassName.methodName (list of parameters) Example int number = (int) (Math.random()*100); If you create a new class Test, you can invoke the max method using int number = TestMax.max(3,5); 32 35 Execute print statement void Method Example If a method does not return any value, it is said to return void type. The method is called a void method The main method is a void method Hello world! ); Program example defines and uses a method which prints the grade for a given score TestVoidMethod.java 33 36
Passing Parameters When calling a method, the arguments must match the parameters in order, number, and compatible type public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) message); nprintln( Hello!, 3); nprintln( So that s how the methods work, 10); When invoking a method, the value of the argument is passed to the parameter. The variable itself is not affected. This is referred to as pass-by-value. 37 Pass by Value 40 somemethod stack x: 4 main stack x: 3 Pass by Value Trace call stack Pass by Value main stack x: 3 somemethod stack x: 4 main stack x: 3 38 41 Pass by Value Pass by Value somemethod stack x: 3 main stack x: 3 main stack x: 3 39 42
Program Example - Pass by Value The program demonstrates the effect of pass-by-value It creates a method for swapping two variables The values of the arguments are not changed after the method is invoked What if we change the method to swap(int num1, int num2) TestPassByValue.java Displaying Prime Numbers - Algorithm Set an initial count to 0 (to track the number of prime numbers) Set an initial number to 2 while (count < 50) { test whether number is prime; if number is prime { print the number; update count; Define a method to test whether a number is prime - check whether it is divisible by 2, 3, 4, up to number/2. PrimeNumberMethod.java 43 Modulizing code Write a method once and reuse it anywhere. Methods can be used to reduce redundant code and enable code reuse Methods can also be used to modularize code and reduce complexity of the program Overloading methods Method overloading: multiple methods can have the same name but different parameter lists Compiler determines which method is used based on the method signature (method name and parameters) 44 Problem Revisited: Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: Start with number 1 Determine whether the number is prime. Print the number if it is prime Count the prime numbers so far. If count < 50, repeat the above steps Overloading Methods return num1; return num2; public static double max(double num1, double num2) { return num1; return num2; max(1, 3); max(1.0, 3.0); max(1.0, 3); 45 48
Scope of Local Variables A local variable: a variable defined inside a method Scope: 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. Scope of Local Variables 49 52 Scope of Local Variables Scope of a Scope of x Scope of a Scope of x 50 int a = 0;... if (a == 1) { int x = 0;... x= + x); int a = 0;... if (a == 1) { int x = 0; //do some calculations on x int x = 2; Error Okay Scope of Local Variables, cont. What does the following method print? public static void method() { int sum = 0; for (int i = 0; i < 5; i++) { int sum = 0; sum += i; sum: + sum); 53 Scope of Local Variables The Math Class Class constants: PI E Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods 51 54
Trigonometric Methods min, max, and abs sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) toradians(double degree) todegrees(double radians) 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 max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. The max, min, and abs methods are overloaded so they work for int, long, float or double 55 58 Exponent Methods exp(double a) Returns e raised to the power of a. log(double a) Returns the natural logarithm of a. log10(double a) Returns the 10-based 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. The random Method random() Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). Examples: In general, 56 59 Rounding Methods double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. double round(double x) x is rounded to its nearest integer. Returns (int)math.floor(x+0.5) Generating Random Characters How do you generate random capital character? Solution: generate random number in range 65-90 57 60
The RandomCharacter Class Generalization We want to generate character from range ch1 to ch2 Remember: characters can be treated as integers (char)(ch1 + Math.random() * (ch2 ch1 + 1)) Design Diagram Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 RandomCharacter.java TestRandomCharacter.java 61 64 Stepwise Refinement 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 to decompose it into subproblems The subproblems can be further decomposed into smaller, more manageable problems Design Diagram readinput printcalendar (main) printmonthtitle getmonthname Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 printmonth printmonthbody getstartday gettotalnumofdays getnumofdaysinmonth isleapyear 62 65 PrintCalender Case Study Write a program that reads year and month and prints out a calendar. Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 PrintCalendar.java Design Diagram readinput printcalendar (main) printmonthtitle getmonthname Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 printmonth printmonthbody getstartday gettotalnumofdays getnumofdaysinmonth isleapyear 63 66
Design Diagram printcalendar (main) Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 readinput printmonth printmonthtitle getmonthname printmonthbody getstartday gettotalnumofdays getnumofdaysinmonth isleapyear 67 Design Diagram printcalendar (main) Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 readinput printmonth printmonthtitle getmonthname printmonthbody getstartday How to get the start day for the first date in a month, assuming we know that Jan 1, 1800, was Wednesday? gettotalnumofdays getnumofdaysinmonth isleapyear 68 Implementation Top-down Implement one method in the structure chart at a time from the top to bottom Stubs can be used for the methods waiting to be implemented Bottom-up Implement one method in the structure chart at a time from the bottom to the top For each method implemented, write a test program to test it 69