Methods

index
BASIC

Methods are used to break up a long program into shorter, carefully named, easier to understand pieces.

For example, the following program computes the average of two numbers entered by the user.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    double number1 = input.nextDouble();
    System.out.print("Enter a number: ");
    double number2 = input.nextDouble();
    double average = (number1 + number2) / 2;
    System.out.println("The average of " + number1 + " and " +
                       number2 + " is " + average);
}

This program is cluttered and difficult to read (blank lines in a couple of places would help, though). Now consider the main method in the following equivalent program:

public static void main(String[] args) {
    double number1 = getANumber();
    double number2 = getANumber();
    System.out.println("The average of " + number1 + " and " +
                       number2 + " is " + average(number1, number2));
}
 
private static double getANumber() {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    return input.nextDouble();
}
 
private static double average(double number1, double number2) {
    return (number1 + number2) / 2;
}

You probably found the main method easier to read in this second version. It is shorter, uses meaningful names (getANumber, average) to help explain what is being done, and avoids duplication of the three lines involved in reading a number. In the above,

  1. The main method "calls" getANumber() to get a double value, and assigns this value to number1.
  2. The main method "calls" getANumber() a second time to get another double value, and assigns this value to number2.
  3. The main method calls average(number1, number2) to compute the average of the two numbers.
  4. The main method concatenates this average value with some Strings, and calls another method System.out.println to display the result.

Basically, all the other methods act as "helpers" to the main method: They scurry around and do whatever main asks them to do. These other methods may call helper minput.nextDouble()ethods of their own, to any level (for example, the getANumber() method above uses as a helper method).

Defining methods

Here is the (slightly simplified) syntax for a method definition:

access optionalStatic returnType methodName(formalParameters) {
    declarations;
    statements;
    return expression;
}

where:

Using methods

Methods may be static methods or instance methods. You can call a static method by first naming the class to which the method belongs:

SomeClass.someMethod(actualParameters)

The class name may be omitted if the method call is in the same class as the method definition.

Instance methods are "called" by first naming the object to which you want to send a message:

someObject.someMethod(actualParameters)

The object name may be omitted when an object is "talking to itself." That is, a non-static method may call another non-static method in the same class, and both methods will be executed by the same object.

Here's how a method call works:

  1. The actualParameters (a list of zero or more expressions) are evaluated.
  2. Java finds the appropriate method like this:
    1. Java figures out to which object or class the message is being sent.
    2. Java finds the method or methods with the correct name and the correct number and types of formal parameters.

  3. Java assigns, to each formal parameter, the value of the corresponding actual parameter.
  4. The body of the method is then executed.
  5. When the method finishes, control is returned to the place from which the method was "called."
    1. If the method was called from within an expression, the returned value is used in the computation of that expression.
    2. If the method was called as a statement (for example, System.out.println), any value returned by the method will be ignored. Methods intended to be used in this way typically return void.

When you define a method, you must specify the type of each formal parameter; but when you call a method, you do not specify the types of the actual parameters. For example,

showValue("pi", Math.PI); // method call

public void showValue(String name, double number) { // method definition System.out.println("The value of " + name + " is " + number); }
STYLE

The names of methods should be verbs or verb phrases. They should begin with a lowercase letter; if the name consists of multiple words, all but the first should be capitalized. Do not use dollar signs or underscores in the name.

The name should describe as accurately as possible what the method does. If what the method does is too complicated to be given a simple, accurate name, then you should break the method up into simpler, more easily named methods.

Methods should generally be short, preferably short enough to see the entire method at once on your computer screen. There is no such thing as a method that is "too short."

INTERMEDIATE

Polymorphism (overloading and overriding methods)

The signature of a method is that which distinguishes it from other methods. In Java, the signature consists of the name of the method, the number of parameters, and the types (in order) of those parameters.

You can have multiple methods in a class with the same name, as long as they have different signatures. This is called overloading the method name.

If a class inherits a method from some superclass, but declares its own method with the exact same signature, this called overriding the inherited method. "Calls" to the method will use the non-inherited version. (If, however, within the class, you wish to use the inherited version, you can prefix it with the keyword super, for example, super.someMethod()).

Exceptions

Any method which may cause a checked exception to occur must either catch that exception with a try statement, or the method must declare that it throws the exception; for example,

public double sqrt(double arg) throws IllegalArgumentException { ... }

If the method may throw more than one type of checked exception, the exception names are separated by commas.

ADVANCED

Parameters must be assignment compatible. In other words, it must be possible to assign the actual parameter value to the formal parameter variable without an explicit cast. For example, if the method definition takes a double formal parameter, and the method "call" has an int actual parameter, the call succeeds, because an int value can be assigned to a double variable.

If the method is overloaded so that one two or more versions are assignment compatible with the actual parameters of a method call, Java chooses the "best match" version to execute. If there is no clear best match, then the call is ambiguous and results in a syntax error.