05slide_2007 - Chapter 5 Methods EE3206/EE5805 Java...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 5 Methods EE3206/EE5805 Java Programming & Application EE3206/EE5805 1 Objectives To declare methods, invoke methods, and pass arguments to To a method. To use method overloading and know ambiguous overloading. To To learn the concept of method abstraction. To To design and implement methods using stepwise refinement. To To determine the scope of local variables. To To know how to use the methods in the Math class. To EE3206/EE5805 Java Programming & Application EE3206/EE5805 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation. Define a method modifier method header method body return value type method name formal parameters Invoke a method public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } parameter list int z = max(x, y); actual parameters (arguments) return value EE3206/EE5805 Java Programming & Application EE3206/EE5805 3 Introducing Methods, cont. • • • Method signature is the combination of the method name and the parameter list. The variables defined in the method header are known 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. 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. • • the returnValueType in the main method is void public static void main(String args) {……} EE3206/EE5805 Java Programming & Application EE3206/EE5805 4 • Calling Methods Listing 5.1 Testing the max method This program demonstrates calling a method max to return the largest of the int values TestMax Run EE3206/EE5805 Java Programming & Application EE3206/EE5805 5 CAUTION A return statement is required for a non-void method. return The following method is logically correct, but it has a compilation error, The because the Java compiler thinks it possible that this method does not return any value. 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 if (n < 0) return –1; } One of the benefits of methods is for reuse. A method can also be One invoked from any other classes. (restricted by certain conditions) You can invoke the static method max using ClassName.methodName You (e.g. TestMax.max). EE3206/EE5805 Java Programming & Application EE3206/EE5805 6 Call Stacks Call Stack is a memory space to hold data of a call when the current scope is switched by invoking other function call. Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 Space required for the main method k: j: 2 i: 5 Space required for the main method k: 5 j: 2 i: 5 Stack is empty The main method is invoked. The max method is invoked. The max method is finished and the return value is sent to k. The main method is finished. EE3206/EE5805 Java Programming & Application EE3206/EE5805 7 animation Trace Call Stack i is declared and initialized 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 8 i: 5 The main method is invoked. animation Trace Call Stack j is declared and initialized 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 9 j: 2 i: 5 The main method is invoked. animation Trace Call Stack Declare k 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 10 Space required for the main method k: j: 2 i: 5 The main method is invoked. animation Trace Call Stack Invoke max(i, j) 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 11 Space required for the main method k: j: 2 i: 5 The main method is invoked. animation Trace Call Stack pass the values of i and j to num1 and num2 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 12 animation Trace Call Stack pass the values of i and j to num1 and num2 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 13 animation Trace Call Stack (num1 > num2) is true 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 result: num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. 14 animation Trace Call Stack Assign num1 to result 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k: j: 2 i: 5 The max method is invoked. EE3206/EE5805 Java Programming & Application EE3206/EE5805 15 animation Trace Call Stack Return result and assign it to k 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } Space required for the max method result: 5 num2: 2 num1: 5 Space required for the main method k:5 j: 2 i: 5 The max method is invoked. EE3206/EE5805 Java Programming & Application EE3206/EE5805 16 animation Trace Call Stack Execute print statement 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 17 Space required for the main method k:5 j: 2 i: 5 The main method is invoked. Pass by Value Listing 5.2 Testing Pass by value This program demonstrates passing values to the methods. TestPassByValue Run EE3206/EE5805 Java Programming & Application EE3206/EE5805 18 Pass by Value, cont. 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 main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Space required for the main method num2: 2 num1: 1 Stack is empty The main method is invoked The swap method is invoked The swap method is finished The main method is finished EE3206/EE5805 Java Programming & Application EE3206/EE5805 19 Overloading Methods Two methods can be declared with the same Two name but different parameter lists (hence different signatures). Compiler identifies the method being invoked by Compiler the method signature. This is called method overloading. This TestMethodOverloading Run EE3206/EE5805 Java Programming & Application EE3206/EE5805 20 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 Ambiguous invocation is a compilation error. public class AmbiguousOverloading { public static void main(String args) { args) System.out.println(max(1, 2)); 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; } } EE3206/EE5805 Java Programming & Application EE3206/EE5805 21 Method Abstraction You can think of the method body as a black box that contains You the detailed implementation for the method. Benefit of Methods Benefit • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity. Optional arguments for Input Optional return value Method Signature Black Box Method body EE3206/EE5805 Java Programming & Application EE3206/EE5805 22 Stepwise Refinement The concept of method abstraction can be applied to the process of The developing programs. Use the “divide and conquer” strategy (a.k.a. stepwise refinement) to Use stepwise decompose a large problem into subproblems. The subproblems can be further decomposed until it becomes manageable. Top-down approach • • • Implement one method at a time from the top to the bottom. Stubs can be used for the methods waiting to be implemented. A stub is a simple but incomplete version of a method. The use of stubs enables you to test invoking the method from a caller. Bottom-up approach • • Implement one method at a time from the bottom to the top. For each method implemented, write a test program (driver) to test it. Both top-down and bottom-up methods are fine. Both approaches implement the methods incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together. EE3206/EE5805 Java Programming & Application EE3206/EE5805 23 Case Study PrintCalender Let us use the PrintCalendar example to demonstrate the stepwise refinement approach. PrintCalendar Ru n EE3206/EE5805 Java Programming & Application EE3206/EE5805 24 Top-Down Design Diagram •Implement the main method first and then use a stub for the printMonth method. For example, let printMonth display the year and the month in the stub. •See the skeleton: PrintCalendarSkeleton.html printCalendar (main) readInput printMonthTitle getMonthName printMonth printMonthBody getStartDay getTotalNumOfDays getNumOfDaysInMonth EE3206/EE5805 Java Programming & Application isLeapYear EE3206/EE5805 25 Scope of Local Variables Local variable Local • a variable defined inside a method. Scope Scope • the part of the program where the variable can be referenced. The scope of a local variable starts from its The declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be local used, but cannot be re-declared in the same scope. EE3206/EE5805 Java Programming & Application EE3206/EE5805 26 Scope of Local Variables, cont. A variable declared in the initial action part of a for loop header variable has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited But in the loop body from its declaration to the end of the block that contains the variable. The scope of i The scope of j public static void method1() { . . for (int i = 1; i < 10; i++) { . . int j; . . . } } EE3206/EE5805 Java Programming & Application EE3206/EE5805 27 Scope of Local Variables, cont. It is fine to declare i in two non-nesting blocks public static void method1() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { x += i; } for (int i = 1; i < 10; i++) { y += i; } } } It is wrong to declare i in two nesting blocks public static void method2() { int i = 1; int sum = 0; for (int i = 1; i < 10; i++) sum += i; } EE3206/EE5805 Java Programming & Application EE3206/EE5805 28 The Math Class Math Class constants: Class • PI •E Class methods: Class • • • • Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods EE3206/EE5805 Java Programming & Application EE3206/EE5805 29 Trigonometric Methods sin(double a) sin(double cos(double a) cos(double tan(double a) tan(double 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: acos(double a) acos(double asin(double a) asin(double atan(double a) atan(double EE3206/EE5805 Java Programming & Application EE3206/EE5805 30 Exponent Methods exp(double a) exp(double Returns e raised to the power of a. log(double a) log(double Returns the natural logarithm of a. log10(double a) log10(double Returns the 10-based logarithm of a. pow(double a, double b) pow(double Returns a raised to the power of b. sqrt(double a) sqrt(double Returns the square root of a. Examples: Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 EE3206/EE5805 Java Programming & Application EE3206/EE5805 31 Rounding Methods double ceil(double x) double x rounded up to its nearest integer. This integer is returned rounded as a double value. double floor(double x) double x is rounded down to its nearest integer. This integer is rounded returned as a double value. double rint(double x) double x is rounded to its nearest integer. If x is equally close to rounded two integers, the even one is returned as a double. int round(float x) int Return (int)Math.floor(x+0.5). long round(double x) long Return (long)Math.floor(x+0.5). EE3206/EE5805 Java Programming & Application EE3206/EE5805 32 Rounding Methods Examples 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.5) returns -3 EE3206/EE5805 Java Programming & Application EE3206/EE5805 33 min, max, and abs max(a, b)and min(a, b) max(a, min(a, Returns the maximum or minimum of two parameters. 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 abs(a) abs(a) Returns the absolute value of the parameter. EE3206/EE5805 Java Programming & Application EE3206/EE5805 34 The random Method random() returns a random double value in the range [0.0, 1.0). random() returns double 0 <= Math.random() < 1.0 <= Examples: (int)(Math.random() * 10) Returns a random integer between 0 and 9. Returns a random integer between 50 and 99. 50 + (int)(Math.random() * 50) In general, In a + Math.random() * b Returns a random number between a and a + b, excluding a + b. EE3206/EE5805 Java Programming & Application EE3206/EE5805 35 ...
View Full Document

This note was uploaded on 01/11/2011 for the course EE 3206 taught by Professor Cwting during the Spring '07 term at City University of Hong Kong.

Ask a homework question - tutors are online