Java Lecture 5

Functions, Procedure --> Methods

  1. In Java, all functions and procedures are declared inside some class
  2. Java (and our book) calls them the methods of the class
  3. The form of method definitions are
  4. <modifiers> <type> Name ( <parameters> ) <modifiers>
    {
       <statements that are the method body>
       <one or more return statements (for a function)>
    }
  5. In this the <type> is the return type of the method. For a function, it is some known type, like int or double or String; for a procedure, the return "type" is void -- that is, it doesn't return anything.
  6. The parameters to the function are each of the form "<type> <name>", and are separated by commas.
  7. The modifiers in front of the type are keywords that modify the definition. The ones that we have seen so far are "public" and "static"
    1. public means that the method is accessible outside of the class (main has to be public)
    2. static means that this definition is the only definition (for now, we will always use static)
  8. The modifiers after the parameter declarations are special keywords. The only ones we have seen so far is "throws IOException", when we used keyboard input.
  9. The return statement is used to return from a method, and for a function, to return a value from the function. Its form is "return <expression>" for a function, and just "return" for a procedure (i.e., a method with return type of void).
  10. Multiple return statements can be placed inside of a method body. The first return statement that is executed during the call to the method is where the method will finish, and return a value. No other statement is executed in a method after a return is executed
  11. A procedure method does not need a return statement. If the end of the method body is reached (i.e., there are no more statements to execute), the method will end and return to its caller. For a function, though, you must have a return statement that returns a value.

Parameters and local variables

  1. Variables declared inside of a method are called local variables
  2. They exist only during each execution of the method. They do not exist in between executions of the same method, so their values do not "carry over" to the next call of the same method.
  3. Their scope is from the point they are declared to the end of the function body.
    1. kind-of. Actually, if you declare them inside of another enclosing block, they exist only in that block.
  4. Parameters actually act like local variables. You can assign to them, and change their value. Once you do that, the value that was passed in through that parameter is lost (inside of the method you are executing). Changing a parameter value does not change anything outside of the method. If you call the method with some variable names as arguments, and then change the parameter values inside of the method, you do not change those outside variables.