Writing a Method

From CompSciWiki
Revision as of 16:22, 6 March 2007 by Umhawwv (Talk | contribs)

Jump to: navigation, search

Method Header

A method header defines your method that your program uses. A method header in Java has three required parts: the return type, the method name, and parameters.

Here is an example of a method header:

public static int add( int a, int b )

Note: the public static portion of the method header is needed, but will not be covered in this COMP 1010 course. More information on what it means will be covered in COMP 1020. For now, just include it in front of all your method headers.

Return Type

A return type defines the type of value returned from calling this method. They can be a primitive variable such as an int, char, or boolean, but they can also be more complex objects. In the example above, the int portion of the method header is the return type. When the method is finished running, it must return a value of type int to the caller of this method. If this method does not return a value, void must be used.

For example:

public static void main( String[] args )

Method Name

The method name uniquely identifies your method. Method names should be meaningful and describe what your method is going to do. For example, a method called add might add two numbers together, and a method called multiply might multiply two numbers together.

When giving your method a name, the same rules apply for naming a variable but with a slightly different naming convention. Method names should contain a verb and if the method name contains more than one word, the first word should be in lowercase and the first letter of every other word should be capitalized. Here are some examples of method names:

add
subtract
printString
deleteFromList

Parameters

Parameters are values that are passed into a method to alter the way the method executes or the value it returns. The parameters must be placed in round brackets after the method name. Here is an example of a method header with two parameters defined:

public static void add( int myInt, char myChar )

In this example, we have two parameters: an integer called myInt and a char called myChar. The two parameters are separated by a comma. You may add as many parameters as you like for a method, as long as they are separated by commas. However, if your parameter list is getting too long, you may want to try and split it up into separate methods if possible.

Methods may also be defined without any parameters. If this is the case, then the method name must be followed by an opening and closing round bracket. For example:

public static void doSomething()

Method Body

Method Body

The method body is the guts of a method and defines how your method will function when called. When creating the body, you do not need to redeclare the variables that were passed by the parameter list. They will already be declared and usable at any time in the method. However, additional variables must be declared before they can be used. Variables declared within the method will be unique to this method and will not be affected by the program outside of this method. The method body must be placed in between a set of opening and closing braces ({ and }) as you would do for the main method and for an if statement.

Returning a Value

If a return type of void was declared in the message header, then no return statement is needed for this method. However, if any other return type was specified, then there must exist a return call in the method body (usually the last line of the method before the closing brace). return is a keyword that tells the program to give a value back to the portion of the program that called this method. The return keyword must be followed by a statement that gives the same type of identifier as the one declared in the message header. Anything that can be assigned to a variable are valid returns.

Here is an example of the same method returning the value in three different ways:

Return with a variable (preferred):

public static int add( int value1, int value2 )
{
    int   sum;  //This will hold the sum of our two values

    //Add the two numbers together
    sum = value1 + value2;

    //Return the sum to the caller of this method
    return sum;
}

Return by doing the calculation on one line:

public static int add( int value1, int value2 )
{
    //Return the sum to the caller of this method
    return value1 + value2;
}

Return by calling another method:

public static int add( int value1, int value2 ) {

   //Call a subtract method and get the value returned from it,
   // then add value1 and value2 to it and return it.
   return subtract(10, 4) + value1 + value2;

}

A common mistake that beginning programmers make is that they put more than one return call in a method body. Take a look at the following method which returns the greater of two numbers that are passed in the parameters:

public static int getGreaterInt( int value1, int value2 )
{
    if ( value1 > value2 )
    {
        return value1;
    }
    else
    {
        return value2;
    }
}

Although this method will work, it should be avoided. Having more than one return in a method body can make debugging harder, can make code harder to read, and can cause unwanted behavior if certain cases are not met. Instead, rewrite the method to only have one return statement:

public static int getGreaterInt( int value1, int value2 )
{
    int biggest; //Declare a variable to hold the biggest int

    if ( value1 > value )
    {
        biggest = value1;
    }
    else
    {
        biggest = value2;
    }

    return biggest;
}