11/11/11

Methods Explanation : Java Tutorial

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.

Creating a Method : 

In general, a method has the following syntax:
 modifier returnValueType methodName(list of parameters) { 

  // Method body;

 }

A method definition consists of a method header and a method body. Here are all the parts of a method:
  • 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.

Note: In certain other languages, methods are referred to as procedures and functions. A method with a nonvoid return value type is called a function; a method with a void return value type is called a procedure.

Example:

Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two:
 /** 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); 

If the method returns void, a call to the method must be a statement. For example, the method println returns void. The following call is a statement:
System.out.println("Welcome to Java!"); 
Example:

Following is the example to demonstrate how to define a method and how to call it:
 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 

This program contains the main method and the max method. The main method is just like any other method except that it is invoked by the JVM.

The main method's header is always the same, like the one in this example, with the modifiers public and static, return value type void, method name main, and a parameter of the String[] type. String[] indicates that the parameter is an array of String.

Here is an example:


      class Box {
             double width;
             double height;
             double depth;

      // A method inside the box class with no parameters.
             void volume() {
                                
                 System.out.print("Volume is ");
                 System.out.println(width * height * depth);
            }
                                                   
      // A method inside the box class with parameters.
                   
            double Vol(double w,double h,double d){

                 double Volume=w*h*d;
                 return Volume; // return the value, return type is 'double'
            }
      }
                                        
      class BoxDemo3 {
            public static void main(String args[]) {
                                                
                   Box mybox1 = new Box();
                   Box mybox2 = new Box();
                                                
       // assign values to mybox1's instance variables
                                                
                   mybox1.width = 10;
                   mybox1.height = 20;
                   mybox1.depth = 15;
                                              
       /* assign different values to mybox2's
          instance variables */
                                                
                   mybox2.width = 3;
                   mybox2.height = 6;
                   mybox2.depth = 9;
                                            
       // display volume of first box
                                                
                   mybox1.volume();
                                               
       // display volume of second box
                                                
                   mybox2.volume();
                                                
       // Calling method with parameter
                       
                   double volm=Vol(mybox2.width,mybox2.height,mybox2.depth);
                   System.out.println("The Volume (got by with parameters method) :" + volm);
                                                
           }
     }
OUTPUT:

Volume is 3000.0 (mybox1)

Volume is 162.0 (mybox2)

The Volume ( got by with parameters method) :162.0

SHARE THIS POST: