Method CIS 1068 Program Design and Abstraction Zhen
Method - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: zhen. jiang@temple. edu 9/25/2020 1
Table of Contents n n n Introduction (use of method) Declaring a method Calling a method Methods calling methods Control flow of method call Generalizing method Parameterization Multiple parameters Parameter mystery Return values (vs. void) Summary 9/25/2020 2
Procedural decomposition using methods 9/25/2020 3
Redundancy in programs n public class Fraggle. Rock { public static void main(String[] args) { System. out. println("Dance your cares away, "); System. out. println("Worry's for another day. "); System. out. println("Let the music play, "); System. out. println("Down at Fraggle Rock. "); } } 9/25/2020 4
n n This is a space & timing problem: to locate the redundancy of any part of program running at any time. Compared with the timing problem in loop: 1 st, 2 nd, 3 rd … iterations Compared with the space problem in arrays: 1 st, 2 nd, 3 rd … elements 1 st, 2 nd, 3 rd … appearances of the same/similar procedure in your program! 9/25/2020 5
finclaration, definition, body public class Fraggle. Rock { public static void sing. Chorus() { System. out. println("Dance your cares away, "); System. out. println("Worry's for another day. "); System. out. println("Let the music play, "); System. out. println("Down at Fraggle Rock. "); } First time, four print lines repeated public static void main(String[] args) { sing. Chorus(); System. out. println(); sing. Chorus(); } The second time, four prints repeated } 9/25/2020 6
n n static method: A group of statements given a name. To use a static method: 1. define it n Write a group of statements and give it a name. 2. call it n (write down the recipe) (cook using the recipe) Tell our program to execute the method. 9/25/2020 7
Method signature public class Fraggle. Rock { Method body public static void sing. Chorus() { System. out. println("Dance your cares away, "); System. out. println("Worry's for another day. "); System. out. println("Let the music play, "); System. out. println("Down at Fraggle Rock. "); } Method call, 1 st time public static void main(String[] args) { sing. Chorus(); System. out. println(); sing. Chorus(); } Method call, 2 nd time } 9/25/2020 8
Declaring a static method n The syntax for declaring a static method: public class <class name> {. . . public static void <method name>() { <statement>; … <statement>; } } 9/25/2020 9
Calling a static method n The syntax for calling a static method (cooking using the recipe): <method name>(); 9/25/2020 10
n Declaring a static method public static void print. Affirmation() { System. out. println("I am good enough!"); System. out. println("I am smart enough!"); System. out. println("People like me!"); } n Calling a static method (possibly multiple times) print. Affirmation(); n Output I am good enough! I am smart enough! People like me! 9/25/2020 11
Methods calling methods Output: n One static method can call another (p 310): public class Methods. Example { public static void main(String[] args) { message 1(); message 2(); System. out. println("Done with main. "); } This is message 1. This is message 2. This is message 1. Done with message 2. Done with main. public static void message 1() { System. out. println("This is message 1. "); } public static void message 2() { System. out. println("This is message 2. "); message 1(); System. out. println("Done with message 2. "); } } 9/25/2020 12
Control flow of methods n When a method is called, the execution n "jumps" into that method executes all of the method’s statements "jumps" back to the statement after the method call 9/25/2020 13
Output: This is message 1. This is message 2. This is message 1. Done with message 2. Done with main. public class Methods. Example { public static void main(String[] args) { message 1(); message 2(); . . . } } public static void message 1() { System. out. println("This is message 1. "); } public static void message 2() { System. out. println("This is message 2"); message 1(); System. out. println("Done with message 2. "); } public static void message 1() { System. out. println("This is message 1. "); } 9/25/2020 14
Example: Figure drawing n Write a program to print the figures. Use static methods to capture structure and eliminate redundancy. ______ / / ______/ +----+ ______ / / | | / STOP ______/ ______ / +----+ 9/25/2020 15
______ / / ______/ +----+ Version 1: Unstructured n Create an empty program with a skeletal header and main method. n Copy the expected output into it, surrounding each line with System. out. println syntax. n Run and verify that it produces the correct output. ______ / | STOP | / ______/ ______ / +----+ 9/25/2020 16
// Suzy Student, CSE 142, Autumn 2047 // This program prints several assorted figures. // public class Figures 1 { public static void main(String[] args) { System. out. println(" ______"); System. out. println(" / \"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println("+----+"); System. out. println(" ______"); System. out. println(" / \"); System. out. println("| STOP |"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println(" ______"); System. out. println(" / \"); System. out. println("+----+"); } } 9/25/2020 17
______ / / ______/ +----+ Version 2: Structured with redundancy ______ / | STOP | / ______/ n Identify the overall structure of the output, and divide the main method into several static methods based on this structure. ______ / +----+ 9/25/2020 18
______ / / ______/ +----+ ______ / | STOP | / ______/ ______ / +----+ 9/25/2020 n Identify the overall structure of the output, and divide the main method into several static methods based on this structure. The structure of the output: n initial "egg" figure n second "teacup" figure n third "stop sign" figure n fourth "hat" figure This structure can be represented by methods: n draw. Egg n draw. Tea. Cup n draw. Stop. Sign n draw. Hat 19
// Suzy Student, CSE 142, Autumn 2047 // Prints several assorted figures, with methods for structure. // public class Figures 2 { public static void main(String[] args) { draw. Egg(); draw. Tea. Cup(); draw. Stop. Sign(); draw. Hat(); } // Draws a figure that vaguely resembles an egg. public static void draw. Egg() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println(); } // Draws a figure that vaguely resembles a teacup. public static void draw. Tea. Cup() { System. out. println("\ /"); System. out. println(" \______/"); System. out. println("+----+"); System. out. println(); } 9/25/2020 20
// Draws a figure that vaguely resembles a stop sign. public static void draw. Stop. Sign() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("| STOP |"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println(); } } // Draws a figure that vaguely resembles a hat. public static void draw. Hat() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("+----+"); } 9/25/2020 21
______ / / ______/ +----+ ______ / | STOP | / ______/ Version 3: Structured without redundancy n Further divide the program to eliminate all redundancy. ______ / +----+ 9/25/2020 22
______ / / ______/ +----+ ______ / | STOP | / ______/ ______ / +----+ 9/25/2020 n Further divide the program to eliminate all redundancy. The redundancy: n top half of egg (purple) n bottom half of egg (green) n divider line (yellow) This redundancy can be fixed by methods: n draw. Egg. Top n draw. Egg. Bottom n draw. Line 23
// Suzy Student, CSE 142, Autumn 2047 // Prints several figures, with methods for structure and redundancy. public class Figures 3 { public static void main(String[] args) { draw. Egg(); draw. Tea. Cup(); draw. Stop. Sign(); draw. Hat(); } // draws redundant part that looks like the top of an egg public static void draw. Egg. Top() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("/ \"); } // draws redundant part that looks like the bottom of an egg public static void draw. Egg. Bottom() { System. out. println("\ /"); System. out. println(" \______/"); } 9/25/2020 24
// Draws a figure that vaguely resembles an egg. public static void draw. Egg() { draw. Egg. Top(); draw. Egg. Bottom(); System. out. println(); } // Draws a figure that vaguely resembles a teacup. public static void draw. Tea. Cup() { draw. Egg. Bottom(); System. out. println("+----+"); System. out. println(); } // Draws a figure that vaguely resembles a stop sign. public static void draw. Stop. Sign() { draw. Egg. Top(); System. out. println("| STOP |"); draw. Egg. Bottom(); System. out. println(); } } // Draws a figure that vaguely resembles a hat. public static void draw. Hat() { draw. Egg. Top(); System. out. println("+----+"); } 9/25/2020 25
BBBBB B B BBBBB AAAA A A AAAAAA A A N N NNN N N Exercise n Write a program to print the block letters spelling "banana". Use static methods to capture structure and eliminate redundancy. AAAA A A AAAAAA A A 9/25/2020 26
Generalizing Method n Consider the task of drawing the following figures: ********************* ***** * * ***** n The lines and figures are similar, but not exactly the same. 9/25/2020 27
public class Stars { public static void main(String[] args) { draw. Line. Of 13 Stars(); draw. Line. Of 7 Stars(); draw. Line. Of 35 Stars(); draw 10 x 3 Box(); draw 5 x 4 Box(); } public static void draw. Line. Of 13 Stars() { for (int i = 1; i <= 13; i++) { System. out. print("*"); } System. out. println(); } public static void draw. Line. Of 7 Stars() { for (int i = 1; i <= 7; i++) { System. out. print("*"); } System. out. println(); } public static void draw. Line. Of 35 Stars() { for (int i = 1; i <= 35; i++) { System. out. print("*"); } System. out. println(); }. . . 9/25/2020 n Observation: Methods are redundant. n n Would constants help us solve this problem? Other ideas? 28
n What if we had the following? n n draw. Line - A method to draw a line of any number of stars. draw. Box - A method to draw a box of any size. main 7 13 draw. Line ************* Character of each repetition 9/25/2020 General format of repetition 29
Parameterization n parameterized method: n n A method that is given extra information (e. g. number of stars to draw) when it is called. The common part of all calls in a generalization: 1 st, 2 nd, 3 rd, … n parameter: A value passed to a method by its caller, mapping the difference of each call. n Examples: n n System. out. println(“*”) or System. out. println(“**”) random. next. Int(10) 9/25/2020 30
n Parameterized method declaration syntax: public static void <name> (<type> <name>) { <statement(s)>; } n The scope of the parameter is the entire method. P 284 n Example: public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } n count’s scope Whenever print. Spaces is called, the caller must specify how many spaces to print. 9/25/2020 31
n passing an argument for parameter: Calling a parameterized method and specifying a value for its parameter(s). P 291 n Parameterized method call syntax: n Example: <name>(<expression>); System. out. print("*"); print. Spaces(7); System. out. print("**"); int x = 3 * 5; print. Spaces(x + 2); System. out. println("***"); Output: * 9/25/2020 ** *** 32
n When the parameterized method call executes: n the value passed to the method is copied into the parameter variable n the method's code executes using that value public static void main(String[] args) { print. Spaces(7); print. Spaces(13); count: } 13 7 public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } 9/25/2020 33
n value semantics: When primitive variables (such as int or double) are passed as parameters, their values are copied into the method's parameter variable. P 287 -291 n Modifying the method’s parameter variable will NOT affect the variable which was passed to the method. . int x = 23; strange(x); System. out. println("2. x = " + x); . . . } public static void strange(int x) { x = x + 1; // modifies my x System. out. println("1. x = " + x); } 9/25/2020 // this x unchanged Output: 1. x = 24 2. x = 23 34
n ERROR: Not passing a parameter to a method that accepts parameters. print. Spaces(); n // ERROR: parameter value required ERROR: Passing a parameter of the wrong type. print. Spaces(3. 7); n // ERROR: must be of type int The parameter must satisfy the domain of the method. 9/25/2020 35
n Change the Stars program to use parameterized methods. public class Stars { public static void main(String[] args) { draw. Line. Of 13 Stars(); draw. Line. Of 7 Stars(); draw. Line. Of 35 Stars(); draw 10 x 3 Box(); draw 5 x 4 Box(); } public static void draw. Line. Of 13 Stars() { for (int i = 1; i <= 13; i++) { System. out. print("*"); } System. out. println(); } public static void draw. Line. Of 7 Stars() { for (int i = 1; i <= 7; i++) { System. out. print("*"); } System. out. println(); }. . . 9/25/2020 36
// Prints several lines of stars. // Uses a parameterized method to remove redundancy. public class Stars 2 { public static void main(String[] args) { draw. Line(13); draw. Line(7); draw. Line(35); } // Prints the given number of stars plus a line break. public static void draw. Line(int count) { for (int i = 1; i <= count; i++) { System. out. print("*"); } System. out. println(); } } 9/25/2020 37
Multiple parameters n n Methods can accept as many parameters as you like. n When the method is called, it must be passed values for each of its parameters. Multiple parameters declaration syntax: public static void <name> (<type> <name>, . . . , <type> <name>) { <statement(s)>; } n Multiple parameters call syntax: <name>(<expression>, . . . , <expression>); 9/25/2020 38
// Prints several lines and boxes made of stars. // Third version with multiple parameterized methods. public class Stars 3 { public static void main(String[] args) { draw. Line(13); draw. Line(7); draw. Line(35); System. out. println(); draw. Box(10, 3); draw. Box(5, 4); draw. Box(20, 7); } // Prints the given number of stars plus a line break. public static void draw. Line(int count) { for (int i = 1; i <= count; i++) { System. out. print("*"); } System. out. println(); } 9/25/2020 39
// Prints a box of stars of the given size. public static void draw. Box(int width, int height) { draw. Line(width); for (int i = 1; i <= height - 2; i++) { System. out. print("*"); print. Spaces(width - 2); System. out. println("*"); } draw. Line(width); } // Prints the given number of spaces. public static void print. Spaces(int count) { for (int i = 1; i <= count; i++) { System. out. print(" "); } } } 9/25/2020 40
Exercise public static void main(String[] args) { print. Number(4, 9); print. Number(17, 6); print. Number(8, 0); print. Number(0, 8); } Output: 44444 171717 0000 9/25/2020 41
public static void main(String[] args) { print. Number(4, 9); print. Number(17, 6); print. Number(8, 0); print. Number(0, 8); } Output: 44444 171717 0000 public static void print. Number(int number, int count) { for(int i=0; i<count; i++) { System. out. print(number); } System. out. println(); } 9/25/2020 42
n Write a method named print. Diamond that accepts a height as a parameter and prints a diamond figure. * ***** * n Write a method named multiplication. Table that accepts a maximum integer as a parameter and prints a table of multiplication from 1 x 1 up to that integer times itself. 9/25/2020 43
n Rewrite the following program to use parameterized methods: // Draws triangular figures of stars. public class Loops { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i - 1; j++) { System. out. print(" "); } for (int j = 1; j <= 10 - 2 * i + 1; j++) { System. out. print("*"); } System. out. println(); } } } 9/25/2020 for (int i = 1; i <= 12; i++) { for (int j = 1; j <= i - 1; j++) { System. out. print(" "); } for (int j = 1; j <= 25 - 2 * i; j++) { System. out. print("*"); } System. out. println(); } 44
// Draws triangular figures using parameterized methods. public class Loops { public static void main(String[] args) { triangle(5); triangle(12); } } // Draws a triangle figure of the given size. public static void triangle(int height) { for (int i = 1; i <= height; i++) { print. Spaces(i - 1); draw. Line(2 * height + 1 - 2 * i); } } 9/25/2020 45
Parameter mystery (value vs. object) n What does this code do? public static void main(String[] args) { int a = 7; int b = 35; System. out. println(a + " " + b); int temp = a; a = b; b = temp; System. out. println(a + " " + b); } 9/25/2020 46
public static void main(String[] args) { int a = 7; int b = 35; System. out. println(a + " " + b); // swap a with b swap(a, b); } System. out. println(a + " " + b); public static void swap(int a, int b) { int temp = a; a = b; b = temp; } n Does this work? Why or why not? 9/25/2020 47
n n n Class type vs. primitive type, P 345! When a primitive type of argument is passed for parameter, the value is copied. A method cannot change the value of an argument. When an object is passed as a parameter, the object is not copied. The same object is referred to by both the original argument and the method's parameter. n 9/25/2020 If a method is called on the parameter, it will affect the original object that was passed to the method. 48
n Object are reference value like this: Dog balto = new Dog(); balto. name = “Balto”; balto: Variable, with slot in memory 9/25/2020 name: breed: “Balto” ? age: ? Reference, a pointer to the object’s data 49
n Example: public static void main(String[] args) { Point p 1 = new Point(2, 3); move(p 1); } public static void move(Point p) { p. set. Location(-1, -2); } p 1 x: -1 2 3 y: -2 p 9/25/2020 50
n What is the output of the following program? public class Mystery { public static void main(String[] args) { int x = 5, y = 9, z = 2; mystery(z, y, x); x: System. out. println(x + " " + y + " " + z); mystery(y, x, z); System. out. println(x + " " + y + " " + z); } x: } y: z: y: public static void mystery(int x, int z, int y) { x++; y = x - z * 2; x = z + 1; System. out. println(x + " " + y + " " + z); } } 9/25/2020 51
n n P 342 -344 Parameters. Demo. java and Demo. Species. java 9/25/2020 52
Return Values (vs. Void) n n return: To send a value out as the result of a method, which can be used in an expression. A return value is like the opposite of a parameter. n n n Parameters pass information in from the caller to the method. Return values pass information out from a method to its caller. How would this be useful? 9/25/2020 53
n Java has a class called Math that has several useful static methods to perform mathematical calculations. Method name Description abs(value) absolute value cos(value) cosine, in radians log(value) logarithm base e log 10(value) logarithm base 10 max(value 1, value 2) larger of two values min(value 1, value 2) smaller of two values pow(base, exponent) base to the exponent power random() random double between 0 and 1 round(value) nearest whole number sqrt(value) square root 9/25/2020 54
n Math method call syntax: Math. <method name>(<parameter(s)>) n Examples: n double square. Root = Math. sqrt(121. 0); System. out. println(square. Root); // 11. 0 int absolute. Value = Math. abs(-50); System. out. println(absolute. Value); // 50 System. out. println(Math. min(3, 7) + 2); // 5 Notice that the preceding calls are used in expressions; they can be printed, stored into a variable, etc… 9/25/2020 55
n n The Math methods do not print results to the console. Instead, each method evaluates to produce (or return) a numeric result, which can be used in an expression. Math. abs -42 42 main 2. 71 3 9/25/2020 Math. round 56
n Evaluate the following expressions: n n n n Math. abs(-1. 23) Math. pow(3, 2) Math. pow(10, -2) Math. sqrt(121. 0) - Math. sqrt(256. 0) Math. ceil(6. 022) + Math. floor(15. 9994) Math. abs(Math. min(-3, -5)) Math. max and Math. min can be used to bound numbers. Consider an int variable named age. n n What statement would replace negative ages with 0? What statement would cap the maximum age to 40? 9/25/2020 57
n Declaring a method that returns a value (p 277): public static <type> <name>(<parameters>) { <statement(s)>; } n Returning a value from a method: return <expression>; n Example: // Returns the given number cubed (to the third power). public static int cube(int number) { return number * number; } 9/25/2020 58
n ERROR: Writing statements after a return statement. public static int increment(int x) { return (x + 1); x = x + 1; // ERROR: statement unreachable! } n ERROR: Confusing the return variable with a variable in the calling method, AKA ignoring the return value. public class Return. Example { public static void main(String[] args) { int x = 1; add. One(x); System. out. println("x = " + x); } public static int add. One(int x) { x = x + 1; return x; } } 9/25/2020 59
n Write a method called is. Factor that accepts two integers as parameters, and returns true if the first is a factor of the second. 9/25/2020 60
n Methods can return different values under different conditions: public static int min(int a, int b) { if (a > b) { return b; } else { return a; } } public static String message(int place) { if (place == 1) { return "You won!"; } else { return "If you're not first, you're last!"; } } 9/25/2020 61
public static int min(int a, int b) { if (a > b) { return b; } } n n The compiler will complain about a "missing return statement". Why? ERROR: Not returning a value in every path. In the above example, what if a <= b? 9/25/2020 62
public static int min(int a, int b) { if (a > b) { return b; } else if (a <= b) { return a; } } n n It still produces the "missing return statement" error. Why? n To our eyes, it is clear that all paths (greater, equal, less) do return a value. n But the compiler thinks that if/else if code might choose not to execute any branch, so it refuses to accept this code. How can we fix it? 9/25/2020 63
n Write a program that prompts the user for a maximum integer and prints out a list of all prime numbers up to that maximum. Here is an example log of execution: Maximum number? 50 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 15 total primes 9/25/2020 64
import java. util. *; public class Print. Primes { public static void main(String[] args) { Scanner console = new Scanner(System. in); print. Primes(get. Number(console)); } public static int count. Factors(int num) { int count = 0; for (int i = 1; i <= num; i++) { if (num % i == 0) { count++; } } return count; }. . . 9/25/2020 65
public static int get. Number(Scanner console) { System. out. print("Maximum number? "); return console. next. Int(); } public static void print. Primes(int max) { int num. Primes = 0; if (max >= 2) { System. out. print(2); num. Primes++; for (int i = 3; i <= max; i++) { if (count. Factors(i) == 2) { num. Primes++; System. out. print(", " + i); } } System. out. println(); } System. out. println(num. Primes + " total primes"); } } 9/25/2020 66
Summary n n n n Procedure decomposition Method declaration, p 277 Method call & control flow n Exercises on slide 26 Scope of local variable, p 284 -285, p 290 Figure drawing, sample code, slides 18 -25 Parameter and argument, p 291 Primitive type (p 291) vs. class type (p 339 -345) n Demo. Species on slide 52 Return (vs. void) , p 277 9/25/2020 67
- Slides: 67