More About Java Methods

Method Overloading

Method Overloading means that it is legal to have more than one method with the same name (in the same class), as long as they have different parameter lists. The difference can be in number of parameters or in the types of parameters.

Example:

   int Process(double num);		  // method 1
   int Process(char letter);              // method 2
   int Process(double num, int position); // method 3
Notice that although all three methods have the same exact name, they each have a different parameter list. The compiler can then distinguish the calls:
   x = Process(3.45, 12);	// invokes the third function above
   x = Process('f');		// invokes the second function

Ambiguous Invocation

Because of function overloading and the legality of some automatic type conversions, it is possible to make a call that could match two methods (due to the type conversion issue). This will result in a compiler error. Example:
  double Sum(int x, double y);
  double Sum(double x, int y);
This pair of methods is legal, since the parameter lists differ. But the following is an illegal call, due to ambiguous invocation:
  System.out.print("The sum is " + Sum(3, 4));

The Math Class

For certain kinds of mathematical calculations, there are many methods available in a pre-built class called Math The Math class API

Recursive Methods

A recursive method is a function that calls itself.

Many tasks can be done with recursion or with iteration. When using recursive functions, one should take care to make sure that there is a "way out". At some point, the function must stop calling itself and be allowed to exit -- and each instance of the function will return to the previous instance (often returning a value).

A typical example: Factorials

n! is defined as n * (n-1) * (n-2) * ... * 1. We can define a factorial function (iteratively) as follows:
   static long Factorial(int n)
   {
      unsigned long f = 1;
      for (int i = n; i >= 1; i--)
         f *= i;

      return f;		// this is the answer
   }
But notice also that:
  n! = n * (n-1)!
By using this formula, we can define a factorial function recursively:
   static long Factorial(int n)
   {
	if (n <= 1)	// base case
	   return 1;
	else
	   return (n * Factorial(n-1));
   }
The function calls itself, but it will eventually stop calling itself once we get down to n = 1. (Notice that each recursive call will invoke the function for a smaller value of n. Namely, n-1 ).

Code Examples