CS 111A Lecture Notes - Methods - Chapter 5
Methods (Functions)
- Think of a long program like AddMoney.java. Wouldn't it be nice
to break that program into pieces so it's easier to understand? We can use a method to do that.
We could put the choice about 1 cent or 1 dollar into a method, to make the main method look
simpler and shorter.
- Think of a repetitive program like this alternative solution to lab
2.
Wouldn't it be nice to define the numeric codes for Rock, Paper, and Scissors in one place for both
players?
We can use a method to do that. We could put those if statements into a method and call it for each
player's move.
- method - a function that is defined as part of a class. In Java, all functions are
defined this way. Like in algebra, a function can take input (arguments) and produce output (return
value). It performs a calculation or executes other code. A function is like a little program; it can
declare its own variables, have its own loops, etc.
- Pre-defined functions, e.g. System.out.print(String), scan.nextInt(), Math.sqrt(double),
Integer.parseInt(String)
- Example on board: you can define your own method to convert Farenheit to Celcius: C=(F-32)*5/9
- method call - a line of code that executes a method. Parenthesis are required. They help
indicate that a method is being called.
- arguments - the data passed into a method when it is called. Also called actual
parameters
- parameters - also called formal parameters - the variables declared in the method
header whose values are initialized by the arguments in the method call.
- return value - the "answer" produced by the method, returned from it to the method call.
- static - indicates that a method does not depend on the existance of an object (it is not
called on an instance of the class). Within the same class, static methods can only call other static
methods.
- Like with variables, method declarations specify the data types for parameters and return value.
When you use (call) a method, no data types are specified (also like when you use variables.)
- Always include a comment next to function's header explaining what it does, what's returned.
- Return statement specifies what the return value is to be. Mandatory if a value is returned.
- Example:FunInterest.java
- In class exercise #1: Write a method to calculate the area of a rectangle, and a main method to test
it by inputting the length and width, calling the method, and outputting the resulting area.
- Area.java: solution to above exercise.
- Call by value -- the default parameter passing mechanism for primitive types. Argument values
plugged in to parameters when control shifts to function.
- Arguments in wrong order cause problems - the order of arguments is how we specify which is which.
- Procedural abstraction - think of functions as black boxes. The rest of the program doesn't care
how a function does what it does. That can even be changed. The interface to the function is all that
needs to be known to make it work. A function can be used to hide sensitive info about how something is
done. (Information Hiding)
- Use functions for subtasks. Design ahead of time using pseudocode or logic diagrams.
Variable Scope
- Parameter names can match argument names, but they don't have to match, because
they are really separate variables.
- Local variables and constants - declared inside a method, accessible only in that function
- Parameters are basically local variables that are initialized by the method call's arguments
Void Functions
- void - a placeholder for a datatype.
- void function - a function whose return type is "void". Means the function returns no value.
Think of it as a procedure - a sequence of commands that are executed to produce output, for example.
- The return statment is optional in a void function. If it does have a return statement, it's
"return;" - no value is returned. Return in this case causes the function to go back to where it was
called from.
- If a void function doesn't have a return statement, the function automatically returns when the
function's closing curly brace } is reached.
- Example: RandomExerciseMethod.java - generates random numbers using a void method.
- In-class exercise #2: Modify your solution to the Nested Brackets in-class exercise from the end of the
Chapter 4 notes (or modify mine) so that in the main method it
asks the user to enter the number of rows and columns, and then the brackets are outputted in a void
method.
- NestedBracketsMethod.java: solution to above exercise.
Functions in a Program
- Every stand-alone program must have a static method called "main", which is the starting and ending
point of the program. The first line that's executed is the first line of main, and when main returns,
the
program ends (unless a GUI interface is used - then System.exit(0) ends the program).
- A program can have any number of functions in addition to main. The other functions are only
executed when they are called. They can be called from main or from any other function.
- Whenever a function returns, execution continues from the point at which it was called (in whichever
function it was called from)
- InflationBetter.java - Uses several methods to calculate
inflation rate.
- In-class exercise #3: Days Out Exercise (a homework assignment I gave
in a previous semester)
- Solution to Days Out Exercise: DaysOut.java
- Static class-level variables and constants - declared inside the class, but not in a method, and available to all methods. Class-level constants (using "final") are fine, but class-level variables are often a bad idea. When a variable could be changed anywhere in the entire class, it's hard to debug it when the value isn't what you expect.
Examples
Return to CS 111A page