«^»
2.8. Methods

In Java, the word method is used instead of function, procedure or subroutine. The argument to println in:

0155: System.out.println(convertToCelsius(82.0));
is convertToCelsius(82.0). This is an example of a call of a method such as:
0156: private static double convertToCelsius(double fahr) {
0157:    return (fahr - 32.0)*5.0/9.0;
0158: }

Unlike C and C++, there is no default return type: you must specify it. If the method does not return a result, void should be used as the return type.

In Java, a parameter of a method behaves like a local variable of the method. It gets its initial value from the argument passed in the call. Any assignment to the parameter within the method only affects the value of the local variable. If a method does not assign a value to the parameter, this can be (and should be) documented by using the final keyword. However, note that this use of final was not permitted in JDK 1.0.x. Here is an example:

0159: private static double convertToCelsius(final double fahr) {
0160:    return (fahr - 32.0)*5.0/9.0;
0161: }

Unlike other languages, a method cannot change the value of the variable that is passed as an argument. So given:

0162: private static void silly(double p) {
0163:    p = p + 4.2;
0164:    System.out.println(p);
0165: }
the following code will not alter the value of the variable a:
0166: a = 2.7;
0167: silly(a);
0168: System.out.println(a);

If a method has no parameters, then it is declared with an empty parameter list:

0169: private static void m() { ... }
and a call has an empty argument list:
0170: m();

It is possible to declare several methods having the same name provided that they can be distinguished by the types of their parameters. This is called method overloading. Here is an example where the name min is declared twice:

0171: private static long min(long a, long b) { return a<b ? a : b; }
0172: private static Date min(Date a, Date b) { return a.before(b) ? a : b; }
At a call of min, the compiler can look at the arguments to see which min is required.

Note: the modifiers private and static will be discussed later.