Lecture 16, CS 302-6, October 10

  1. Review
    1. Methods

                                                               i.      As black box

1.      Something I’d like to emphasize: Methods do ONE thing

                                                             ii.      Declaring, Using

                                                            iii.      Parameters/arguments, return values

                                                           iv.      Fyi: http://99-bottles-of-beer.net/

  1. Void methods
    1. Declare method as ‘void’ (instead of return type)

                                                               i.      For instance, main method

                                                             ii.      Other examples – methods that just print things, etc

    1. End with return; or just with }

                                                               i.      Neither is really better/preferred

    1. Can still have return; in the middle to exit early
    2. Using void methods: method(); (not something=method();)
    3. Example – Drawer.java
  1. Technical details of parameters
    1. Parameter ‘variable’ and parameter ‘value’
    2. Pass by value, not reference

                                                               i.      Changing a value in a method does not change the value in the method that called it

    1. Variable names in separate blocks are separate
  1. More on return statements
    1. Can return literals, variables, expressions, etc…
    2. Immediately exits the method call
    3. You can use return; at different points in a method call

                                                               i.      Example – safe divide method.  Return early if /0.  Else perform divide

    1. Watch out for – unreachable code, branches without returns
    2. Watch out for – make sure to STORE return value, not just compute it.

                                                               i.      dollars=addInterest(dollars);

  1. Stepwise refinement
    1. Think of your program as a sort of flowchart – you want to think of each possible case, and what happens after it
    2. http://xkcd.com/627/

                                                               i.      Each square is a method.  Each diamond is a condition.  The lines are branches

    1. Example – LeapYear.java (not finished yet)

                                                               i.      Via stepwise refinement – think about each possible case

                                                             ii.      Begin by describing conditions for leap year

  1. HW
    1. Read 5.6-5.7