COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi
Chapter 4 Loops for while do-while Last Week
Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of variables Objectives
Methods
Motivation Suppose we want to write a program to find the sum of integers from 1 to 10 from 20 to 30 from 35 to 45
Naïve Solution Obvious solution int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum);
Refactor What about some refactoring? int sum = 0; for (int i = x 1 ; i <= 10; y i++) sum += i; System.out.println("Sum from x 1 to 10 y is " + sum); sum = 0; for (int i = 20; x i <= 30; y i++) sum += i; System.out.println("Sum from 20 x to 30 y is " + sum); sum = 0; for (int i = 35; x i <= 45; y i++) sum += i; System.out.println("Sum from 35 x to 45 y is " + sum);
Solution A better approach is to use a method modifier output name input Method body public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;
Invoking a Method First, a method should be defined Then we can use the method i.e. calling or invoking a method public static void main(string[] args) { int total1 = sum(1, 10); int total2= sum(20, 30); int total3 = sum(35, 45); int total4 = sum(35,1000);
Invoking a Method When calling a method within the same class, we directly call the method public class TestClass{ public static void main(string[] args) { int total1 = sum(1, 10); //---------------------------------------------- public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; calling directly
Invoking a Method When calling a method from another class, use class name if a static method public class AnotherClass{ public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; public class TestClass{ public static void main(string[] args) { int total1 = AnotherClass.sum(1, 10); Class name
Invoking a Method When calling a method from another class, use class name if a static method public class AnotherClass{ public int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; public class TestClass{ public static void main(string[] args) { AnotherClass a = new AnotherClass(); int total1 = a.sum(1, 10); Instance name
So Method is A collection of statements grouped together to perform an operation To use a method We invoke the method E.g. int result = sum(1,10);
Method Signature Method signature Combination of the method name and the parameter list Method header signature public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;
Parameters Parameters Formal parameter public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; public static void main(string[] args) { int total1 = sum(1, 10); Actual parameter
Parameters Formal parameters: Variables defined in the method header Actual parameters: When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
Output If the method does not return a value, the return type is the keyword void. It means nothing will be returned A method may return a value: Use return keyword to return the value E.g. return sum; return keyword is required if return type is anything other than void
Tip A return statement is not required for a void method. return still can be used for terminating the method This is not often done
Programming Style Use return only once in a method! Easier to debug and trace public int max(int x, int y) { if (x > y) return x; else return y; Two exit points public int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result; One exit point: This is better
Program This program demonstrates calling a method max to return the largest value among a set of values. TestMax Run
Program Passing arguments public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace i is now 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace j is now 2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace invoke method max(i,j) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace pass the value of i to x pass the value of j to y public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace Declare variable result public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace (x > y) is true because (5 > 2) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace result is now 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace return result which is 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace return max(i, j) and assign the return value to k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Program Trace finished public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;
Modularizing Code Methods reduce redundant coding and enable code reuse. Methods modularize code and improve the quality of the program. PrimeNumberMethod Run
Previously Chapter 5 Methods Input arguments Output
Today Methods Overload Memory management
Program Write a method that converts a decimal integer to a hexadecimal. Decimal2HexConversion Run
Program Explained Converting a decimal number x (e.g. 74) into a hexadecimal number (e.g. 4A) 1. Divide x by 16 2. Save remainder and quotient 3. Repeat step 1 and 2 until quotient is 0 4. Form the hexadecimal number from remainders (the most recent remainder will be the leftmost digit)
Memory & Methods
Stack A data structure Last in, first out (LIFO) Two basic operation Pop Push Push Pop Z Y x
Memory How memory is arranged 1. Registers Inside the processor, very limited, you have no direct access 2. RAM Stack memory Inside RAM, very fast, lifetime of objects should be known, all primitive variables placed here Heap memory Inside RAM, reference values placed here 3. Constant values Will be directly replaced in code
Revisiting Program Each time a method is called, the system stores parameters and variables in stack memory. Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); return result;
Memory How memory is managed? Space required for max method: x:5 y:2 Space required for max method: Result: 5 x:5 y:2 Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: 5 i:5 j:2 Stack is empty
Pass by Reference What about reference types? E.g. Random r = new Random(); Actual Object Space required for main method: r (reference) Stack Memory Heap Memory
Pass by Reference What about reference types? E.g. Random r = new Random(); Space required for test method: x Space required for main method: r (reference) Stack Memory Actual Object Heap Memory
Passing Arguments If primitive types are passed Value is passed Changes inside method will not affect the variable If a reference type is passed Reference is passed (address of memory location containing actual object) Changes inside the method will affect the variable
Method Overload
Method Overload Different versions of the same method accepting different arguments TestMethodOverloading Run
Tip Method overload is only based on input arguments Method overload can not be based on different output values Method overload cannot be based on different modifiers
Method Overload 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.
Ambiguous invocation public class AmbiguousOverloading { public static void main(string[] args) { System.out.println(max(1, 2)); public static double max(int num1, double num2) { double result = 0; if (num1 > num2) result = num1; else result = num2; return result; public static double max(double num1, int num2) { double result = 0; if (num1 > num2) result = num1; else result = num2; return result;
Variable Scope
Variable Scope Scope: Part of the program where the variable can be referenced. A local variable: A variable defined inside a method. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable.
Variable Scope A variable declared in the initial action part of a for loop has its scope in the entire loop. 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. The scope of i The scope of j public static void method1() {.. for (int i = 1; i < 10; i++) {.. int j;...
Variable Scope You can declare a local variable with the same name multiple times in different nonnesting blocks in a method You cannot declare a local variable twice in nested blocks.
Variable Scope A variable declared in a method 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;
Method Abstraction
Abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Optional arguments for Input Optional return value Method Header Method body Black Box
Method Benefits Write a method once and reuse it anywhere. Hide the implementation from the user. Change it without affecting the user Reduce complexity.
Method Benefits Example Math class provides many methods Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods
Stepwise Refinement When writing a large program, you can use the divide and conquer strategy, also known as stepwise refinement, to decompose it into sub-problems. The sub-problems can be further decomposed into smaller, more manageable problems. Main Task Task 1 Task 2 Task 1-1 Task 1-2 Task 3
Stepwise Refinement An example to demonstrate the stepwise refinement approach: PrintCalendar Run
Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear
Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear
Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear
Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear
Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear
Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear
Top Down Design Top-down approach is to implement one method in the structure chart at a time from the top to the bottom. Implement the main method first and then use a stub for each one of the methods. 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. A Skeleton for printcalendar
Bottom Up Design Bottom-up approach is to 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.
Comparison 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.
Program Revisited An example to demonstrate the stepwise refinement approach: PrintCalendar Run
Program As introduced before, each character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal). To generate a random character is to generate a random integer between 0 and 65535. The Unicode for lowercase letters are consecutive integers starting from the Unicode for 'a', then for 'b', 'c',..., and 'z'. A random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as follows: Random r = new Random(); char x = ch1 + r.nextint(ch2 ch1 + 1)
Program Random character generator RandomCharacter TestRandomCharacter Run
Math Class
Math Class Class constants: PI E Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods
Math Class Trigonometric methods sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) 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 Radians
Math Class 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.
Math Class 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 rint(double x) 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).
Rounding 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.6) returns -3 Math Class
Math Class Min, max, etc max(a, b) and min(a, b) Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0).
Math Class random method Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). (int)(math.random() * 10) 50 + (int)(math.random() * 50) Returns a random integer between 0 and 9. Returns a random integer between 50 and 99. a + Math.random() * b Returns a random number between a and a + b, excluding a + b.