Lecture 16, CS 302-7 and 8, February 27

 

  1. Review
    1. Methods

                                                               i.      As black box

1.      Methods should be designed to do one discrete thing

                                                             ii.      Declaring, Using

                                                            iii.      Parameters/arguments, return values

  1. Parameters, arguments, return values
    1. Number – 0 or 1 return, any number of args
    2. Type – specify. Can be primitive or class type
    3. Bottles.java
    4. Fyi: http://99-bottles-of-beer.net/
  2. 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 – you’ll see both

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

                                                               i.      Parameter variable in method declaration

                                                             ii.      Parameter value when you call the method

    1. 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
    2. CallStack.java
  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.
  1. HW
    1. Read 5.6-5.7