Saturday, September 1, 2012

Creating a Method:



syntax: modifier returnValueType methodName(list of parameters) { // Method body; }

Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.

Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.

Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.

Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

Method Body: The method body contains a collection of statements that define what the method does.

Example:

/** Return the max between two numbers */

public static int max(int num1, int num2) {

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

Calling a Method:

In creating a method, you give a definition of what the method is to do. To use a method, you have to call or invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not.

When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached. If the method returns a value, a call to the method is usually treated as a value.

For example: int larger = max(30, 40);

Example

public class TestMax {

/** Main method */

public static void main(String[] args) {

int i = 5;

int j = 2;

int k = max(i, j);

System.out.println("The maximum between " + i + " and " + j + " is " + k);

}

/** Return the max between two numbers */

public static int max(int num1, int num2) {

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

This would produce following result:

The maximum between 5 and 2 is 5

No comments: