Java Lecture 5
Functions, Procedure --> Methods
- In Java, all functions and procedures are declared inside some class
- Java (and our book) calls them the methods of the class
- The form of method definitions are
<modifiers> <type> Name ( <parameters> ) <modifiers>
{
<statements that are the method body>
<one or more return statements (for a function)>
}
- 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.
- The parameters to the function are each of the form "<type> <name>",
and are separated by commas.
- 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"
- public means that the method is accessible outside of the class (main
has to be public)
- static means that this definition is the only definition (for now,
we will always use static)
- 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.
- 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).
- 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
- 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
- Variables declared inside of a method are called local variables
- 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.
- Their scope is from the point they are declared to the end of the function
body.
- kind-of. Actually, if you declare them inside of another enclosing
block, they exist only in that block.
- 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.