Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield.

Similar presentations


Presentation on theme: "1 Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield."— Presentation transcript:

1 1 Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield

2 2 Preparation  Scene so far has been background material and experience Computing systems and problem solving Variables Types Input and output Expressions Assignments Using objects Standard classes and methods Decisions (if, switch) Loops (while, for, do-while)  Next: Experience what Java is really about Design and implement objects representing information and physical world objects

3 3 Object-oriented programming  Basis Create and manipulate objects with attributes and behaviors that the programmer can specify  Mechanism Classes  Benefits An information type is design and implemented once  Reused as needed No need reanalysis and re-justification of the representation

4 4 Known Classes  Classes we’ve seen BigInteger String Rectangle Vector Scanner System  Classes we’ll be seeing soon BigDecimal  But the first step is on creating methods…

5 5 Methods

6 6 Methods we’ve seen  We’ve seen methods (functions) before angleSin = Math.sin (90 * PI/180.0); System.out.println (“Hello world”); value = card.getBlackjackValue();  We are going to start defining them  Note that many of these “return” a value Math.sin() and card.getBlackjack()  The way to name methods is the same as variables allTheWordsTogether With the first letter of each word capitalized Except the very first letter is lower case

7 7 Our first class with methods public class Methods1 { public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt(); if ( value == 1 ) validValue(); else if ( value == 2 ) validValue(); else if ( value == 3 ) invalidValue(); else if ( value == 4 ) invalidValue(); else validValue(); }

8 8 Our first class with methods, continued public static void invalidValue() { System.out.println ("You have entered an invalid value."); System.out.println ("The program will now exit."); System.exit (0); } public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0); }

9 9 Program Demo Methods1.java Methods1.java

10 10 public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0); } public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt(); if ( value == 1 ) validValue(); //... } What’s happening there Scanner stdinvalue 1

11 11 Notes on these methods  At this point, all methods in the class are static We will be discussing what static means later in this slide set Until then, I’ll be ignoring it, and just telling you when things should and should not be static  Sorry!  None of those two methods return a value Notice the “void” before the method name  And none take in any parameters Notice the empty parameters after the method name

12 12 End of lecture on 12 March 2007

13 13

14 14 A previous HW J3

15 15

16 16 Revamping last semester’s HW J3 Start over Public danger Defense contractor Promoted Cynical guru Become a coder Done tech support? Been a sysadmin? Worked with NT? Want to play w/nukes? Hate people? Bitter yet? Successful managing? Start here Start over  A revised HW 3 flowchart  Green paths are “yes” paths, red are “no” paths  We’ll make a slight modification to the diagram:  Note that this part is repeated twice!

17 17 HW J3 Code  The yellow boxed part is what was repeated from the previous slide if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) ) if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL); else System.out.println (A_PROMOTED); else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) { System.out.println (A_CODER); } else if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER);

18 18 HW J3 Code with methods  The yellow boxed part is what was repeated from the previous slide if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) ) if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL); else System.out.println (A_PROMOTED); else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) { System.out.println (A_CODER); } else doBottomPartOfFlowchart(); } else doBottomPartOfFlowchart();

19 19 HW J3 Code with methods  The doBottomPartOfFlowchart method: public static void doBottomPartOfFlowchart() { if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); }

20 20 What happened here  We took a common set of code Wrote it once But used it multiple times (twice in this case)  Granted, the code was a small segment (7 lines) But, in other programs, could be very large  This is called Refactoring It is an essential principle of software engineering Has other names: factoring (notice there is no ‘re’ at the beginning), extracting a method, etc.

21 21 Pros of Refactoring  Benefits of Refactoring Reduce length of code  As you don’t have to repeat that section of code multiple times Make code easier to read  The main if-else-if statement is shorter, thus easier to understand what’s going on Changes are easier to make  If we want to modify that part of the flowchart, we only have to do it once Rather than searching for each of the repeated code segments in a program

22 22 Cons of Refactoring  Drawbacks of Refactoring Because you are calling another method, it will be slightly slower  On the order of a few nanoseconds  Modern compilers can sometimes eliminate this penalty  The general consensus is that the benefits of Refactoring far outweigh the drawback(s)

23 23

24 24 Return Values

25 25 The return keyword  The return keyword immediately stops execution of a method And jumps back to whatever called that method And possibly returns a value (we’ll see this next)  Consider the following method public static void foo (int x) { if ( x == 1 ) return; System.out.println (“x is not 1”); }  This method will only print the String if x is not 1

26 26 Return values  At some point in those methods, Java must be told to take a value and “pass” it back  Consider angleSin = Math.sin (90 * PI/180.0); At some point in the Math.sin() method, the sin has been computed And that value must be “passed back” to be stored in angle  Consider value = card.getBlackjackValue(); At some point in the card.getBlackjackValue() method, the value has been computed And that value must be “passed back” to be stored in value  This is called “returning” a value from a method  Note that some methods don’t return a value System.out.println(), for example

27 27 Return values (aka return types) public class Methods2 { public static int returnsAValue () { return 1; } public static double alsoReturnsAValue() { return 1.0; } public static void main (String args[]) { int value1 = returnsAValue(); System.out.println (value1); double value2 = alsoReturnsAValue(); System.out.println (value2); // The following line requires a cast int value3 = (int) alsoReturnsAValue(); System.out.println (value3); } }

28 28 Program Demo Methods2.java Methods2.java

29 29 Return types  All a return statement does is take the value Which could be a number Or a value in a variable Or an expression (such as x+1)  And “pass” it back to whatever called the method

30 30 How well do you feel you understand return values? a) Very well! This stuff is so easy. b) With a little review, I’ll be good. c) Not very well at all. d) I’m so lost. What’s a return type again? e) I’d rather not answer this question, thanks.

31 31 Parameters  Sometimes you need to pass in parameters to tell a method how to perform Consider Math.sin() – it needs to know the angle  The parameters are listed between the parenthesis after the method name public static void main (String args[])  The methods we will study next compute (and return) x 2, x 3, and x 4

32 32 The methods public static int square (int x) { int theSquare = x * x; return theSquare; } public static int cube (int x) { return x * x * x; } public static int fourthPower (int x) { return square(x) * square(x); }

33 33 A method with multiple parameters public static int squareOrCube (int which, int value) { if ( which == 1 ) return value * value; else if ( which == 2 ) { int cube = value * value * value; return cube; } else return 0; }

34 34 The main() method import java.util.*; public class Methods3 { // the previous methods go here public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter an int value"); int value = stdin.nextInt(); int theSquare = square(value); System.out.println ("Square is " + theSquare); System.out.println ("Cube is " + cube (value)); System.out.println ("Square is " + squareOrCube (1, value)); System.out.println ("Cube is " + squareOrCube (2,value)); System.out.println ("Fourth power is " + fourthPower (value)); } }

35 35 Program Demo Methods3.java Methods3.java

36 36

37 37 Returning objects  We can also return objects from methods What gets returned is the reference to the object public class Methods4 { public static String getCourse () { String name = "CS 101"; return name; } public static void main (String args[]) { String courseName = getCourse(); System.out.println (courseName); } } String “CS 101” courseName name

38 38 End of lecture on 14 March 2007  Tom Horton covered my class today

39 39 Program Demo Methods4.java Methods4.java

40 40 Modifying parameters  Consider the following code public class Methods5 { public static void changeValue (int x) { x = 7; } public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y); } }  What gets printed?

41 41 Program Demo Methods5.java Methods5.java

42 42 Pass by value  Java is a pass-by-value language  This means that a COPY of the parameter’s value is passed into the method If a method changes that value, only the COPY is changed Once the method returns, the copy is forgotten And thus the change is not visible outside the method  There are other manners of returning values that are used in other languages Pass by reference Pass by name (nobody uses this anymore)  We will see about trying to change object parameters later in this slide set

43 43 How well do you feel you understand parameters? 1. Very well! This stuff is easy! 2. Fairly well – with a little review, I’ll be good 3. Okay. It’s not great, but it’s not horrible, either 4. Not well. I’m kinda confused 5. Not at all. I’m soooooo lost

44 44 Variable scoping  A variable is visible within the block it is declared Called the “scope” of the variable public class Scoping { static int z public static void foo (int x) { //... } public static void bar () { //... } public static void main (String[] args) { int y; //... } } This local variable is visible until the end of the main() method This variable is visible anywhere in the Scoping class This parameter is visible only in the foo() method

45 45 How well do you feel you understand variable scoping? 1. Very well! This stuff is easy! 2. Fairly well – with a little review, I’ll be good 3. Okay. It’s not great, but it’s not horrible, either 4. Not well. I’m kinda confused 5. Not at all. I’m soooooo lost

46 46 Method notes summary  You can put the methods in a class in any order Java doesn’t care which one is listed first Thus, you can call a method listed later in the method  This is different than C/C++  All methods must specify a return type If it’s void, then no value is returned  Parameters can’t be changed within a method Although the objects that the parameters point to can be

47 47 Agricultural history Agricultural history Physics Physics Medicine Medicine Literature Literature Peace Peace Economics Economics Chemistry Chemistry Biology Biology Nutrition Nutrition Fluid dynamics Fluid dynamics The 2005 Ig Nobel Prizes “The Significance of Mr. Richard Buckley’s Exploding Trousers” The pitch drop experiment, started in 1927 Neuticles – artificial replacement testicles for dogs The 409 scams of Nigeria for a “cast of rich characters” Locust brain scans while they were watching Star Wars For an alarm clock that runs away, thus making people more productive “Will Humans Swim Faster or Slower in Syrup?” For cataloging the odors of 131 different stressed frogs To Dr. Yoshiro Nakamats who catalogued and analyzed every meal he ate for the last 34 years (and counting) “Pressures Produced When Penguins Pooh – Calculations on Avian Defaecation”

48 48 More on parameter passing

49 49 Modifying parameters  Consider the following code public class Methods5 { public static void changeValue (int x) { x = 7; } public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y); } }  What gets printed? 5 is printed 5 y 5 x 7 x

50 50 Program Demo Methods5.java Methods5.java

51 51 Pass by value  Java is a pass-by-value language  This means that a COPY of the parameter’s value is passed into the method If a method changes that value, only the COPY is changed Once the method returns, the copy is forgotten And thus the change is not visible outside the method  There are other manners of returning values that are used in other languages Pass by reference Pass by name (nobody uses this anymore)  We will see about trying to change object parameters later in this slide set

52 52 Modifying parameters  Consider the following code import java.awt.*; public class Methods6 { public static void changeValue (Rectangle r) { r.setSize (10,20); } public static void main (String args[]) { Rectangle rect = new Rectangle(1, 2); changeValue(rect); System.out.println (rect.getWidth()); } }  What gets printed? 10 is printed + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth () Rectangle - width = 1 - height = 2 rect + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth () Rectangle - width = 10 - height = 20 r

53 53 Program Demo Methods6.java Methods6.java

54 54 Fan-supplied demotivators!

55 55 Pass by value  Java is still a pass-by-value language  This means that a COPY of the parameter’s value is passed into the method But the parameter is a REFERENCE to an object The object itself is not passed So any changes to the reference are forgotten about But you can modify the object it refers to

56 56 Modifying parameters  Consider the following code import java.awt.*; public class Methods7 { public static void changeValue (Rectangle r) { r = new Rectangle (10,20); } public static void main (String args[]) { Rectangle rect = new Rectangle(1, 2); changeValue(rect); System.out.println (rect.getWidth()); } }  What gets printed? 1 is printed + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth() Rectangle - width = 1 - height = 2 rect + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth() Rectangle - width = 10 - height = 20 r The only change!

57 57 Program Demo Methods7.java Methods7.java

58 58 Pass by value  Java is still a pass-by-value language  This means that a COPY of the parameter’s value is passed into the method But the parameter is a REFERENCE to an object The object itself is not passed So any changes to the reference are forgotten about But you can modify the object it refers to

59 59 How well do you feel you understand parameter passing? 1. Very well! This stuff is easy! 2. Fairly well – with a little review, I’ll be good 3. Okay. It’s not great, but it’s not horrible, either 4. Not well. I’m kinda confused 5. Not at all. I’m soooooo lost

60 60 A frisbee demo of parameter passing…

61 61 How well do you feel you understand parameter passing? 1. Very well! This stuff is easy! 2. Fairly well – with a little review, I’ll be good 3. Okay. It’s not great, but it’s not horrible, either 4. Not well. I’m kinda confused 5. Not at all. I’m soooooo lost

62 62 Today’s demotivators


Download ppt "1 Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield."

Similar presentations


Ads by Google