Writing a Method

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > User-Defined_Methods

Introduction

A method consists of two parts: the method header and the method body. Each part is further broken down into smaller parts which are essential to describing what your method does, how your method will be called, what your method will process, and what your method will return.

Method Header

The method header defines certain facets of the method that your program will use. 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 the COMP 1010 course. More information on what public static 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. Examples are int, char, boolean, and String. 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 begin with 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 

The concept of beginning a method name with a verb is quite intuitive: Unlike a variable, which simply represents a value or item, a method performs a set of actions. Hence, the name needs to convey that the method does something. Here are some examples of method names:

 public static void theResult(String info) // Does not begin with a verb.
pubilc static void printResult(String info) // Good example.

public static int maxValue(int a, int b) // Is not a verb.
public static int calculateMax(int a, int b) // Good example.

public static String stars(int numStars) // Does not begin with a verb.
public static String createStarPattern(int numStars) // Good example. 

Notice how the method names that begin with verbs convey the method's purpose better. For example, notice how descriptive printResult is compared to theResult. A method called theResult may print the result, calculate the result, fetch the result from a database, or do any number of things involving a result. But with printResult, we at least know that the result is printed somewhere.

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 the method. However, if any other return type is 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 exit the method and 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 to 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, using return statements in this way 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 contain only 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;
 } 

In general, all methods should exit at only one point and there should not be any code after the return statement. When you omit the return statement in a method with a void return type, the exit point is at the closing brace }.

Example Program

Here is an example program with different method headers, method bodies, and returns:

public class SampleProgram
{
	//This method prints a string. It returns void (nothing) and
	// takes a string as a parameter
	public static void printString( String value )
	{
		System.out.println( value );
	}

	//This method takes two ints and adds them together. The sum is
	// returned.
	public static int add( int value1, int value2 )
	{
		int sum;

		sum = value1 + value2;

		return sum;
	}

	//This method takes two numbers and subtracts them. The difference
	// is returned. Notice how the return does the calculation on the
	// same line.
	public static int subtract( int value1, int value2 )
	{
		return value1 - value2;
	}

	//This method will subtract the first two parameters, and then add
	// the third parameter to the difference and return it. This is an
	// example of using a method call in the return statement. Notice how
	// confusing this return statement can get, even for a method so simple. For simplicity    
       // and clarity avoid calling methods in the return statement. 
	public static int addAndSubtract( int value1, int value2, int value3 )
	{
		return add( subtract( value1, value2 ), value3 );
	}

	//Our main method will call the methods we made
	public static void main( String[] Args )
	{
		//Declare some variables
		int		intNum1;
		int		intNum2;
		int		intNum3;
		String	sentence;

		//Initialize them
		intNum1 = 10;
		intNum2 = 30;
		intNum3 = 13;

		sentence = "The lazy dog didn't jump over the cow, because he was lazy.";

		//Print our sentence
		printString( sentence );

		//Print the sum of intNum1 and intNum2. Note that we can't use the printString
		// method to print it because the printString method takes a String as a parameter,
		// not an int
		System.out.println( add( intNum1, intNum2 ) );

		//Print the difference of intNum3 and intNum1
		System.out.println( subtract( intNum3, intNum1 ) );

		//Print the results of the last method
		System.out.println( addAndSubtract( intNum1, intNum2, intNum3 ) );
	}

}