6.6 Methods


[access modifier] [modifier] return type method-name(arguments) {
method body


The optional access modifier is one of the following keywords: private, private protected, protected, public, or friendly. These control how other classes (other than the one containing the method) may access the method. In all cases, methods in a class can call other methods in a class. Here is the run-down:
only methods in this class may use this method.
private protected
classes that inherit (extend) this class may call this method.
classes that inherit this class, and other classes in the same .java file may use this method.
all classes may use this method.
all classes in this .java file may call this method
The friendly modifier is the default if none is given.

The other possible modifiers are: static and final. A static method is a class method, whereas the default is an instance method. You will want to see the discussion on instance and class members to clear this up. A final variable is one that never changes. For example, Math.E would be declared final. A final method would be compiled inline, so each occurence of a call to the method in your code would be replaced by the body of the method itself. This makes for a faster method call (it eliminates the overhead of a method call) but will bloat your code if you use it too often (you will have several copies of the same method in you compiled Java code).

A Java method's return type can be any valid Java data type. In particular, it could be a primitive Java type, or it could be a class. If you don't want your method to return anything, use the void data type. Otherwise, your method must exit with a return statement. For example, if the method f were of type double, the line return 4.3; would be an acceptable way to exit the method.

The argument list arguments is a comma separated list of simple variable declarations that make up the values you want passed to your method. For example, in our Newton's method code, we had the method declaration:

    static double f(double x) {
	return Math.sin(x);
If f took two doubles for its arguments, you could declare it with:
    static double f(double x, double y) {

    ... code here ...

Next 6.7 Arithmetic, String, and Other Operators

David Maxwell, who is still writing this, would like to hear your comments and suggestions.