Value-returning Methods


What is a return method?

We have touched on this already, but a value-returning method is a method that can send a value back to the statement which called it.

You are already experienced at using value-returning methods. For example, Integer.parseInt() is a value returning method...

int num;

num = Integer.parseInt("700");

The second line passes the String “700” argument into the method. The method returns the int value 700, which is assigned to the num variable by the = operator.

Defining a value-returning method

To create your own value-returning method, you must decide what type of value the method will return. This is because it will be part of your method header! This time, instead of “void” though, we will specify the data type that is being returned.

For example, this method adds two numbers together and returns the result...

/**

 * Sums two integers together.

 * @param numA The first number to be summed

 * @param numB The second number to be summed

 * @return The sum of the two arguments

 */

public static int sum(int numA, int numB) {

   int result = numA + numB;

   return result;

} // end sum

IMPORTANT: The return statement must also be returning a value with the same data type specified in the method header, or a data type otherwise compatible with it. If this condition is not fulfilled, a compiler error will occur. Java will automatically widen the value of the return expression, if necessary, but will never narrow it.

Calling a value-returning method

It’s the same as any other method. The key to note is that since the method returns something, the return value should likely be stored in a variable somewhere, unless the value is just being printed or written to a file.

For example, using the sum() method from earlier...

int sumNum = sum(1, 2);

Now the result of sum(), 3, can be used in the program by referencing sumNum, which holds the returned value from the call sum(1, 2).

Using the sum() method from earlier to print the result to the console...

System.out.print(sum(1,2));

Now the result of sum(), 3, will be printed to the console. This result cannot be used later, as it was not stored!

Documenting return

If our methods have return statements, we need to add the @return tag to our comments. This should come after all @param tags. The comment should only have one @return explanation, to describe the context of what is being returned.

The general format of a method header with a return statement...

/**

 * Purpose of the method goes here…

 * …

 * @return A brief description of what is being returned. Notice the  

 *         data type does not have to be specified.

 */