Course Content‎ > ‎Session 3‎ > ‎

Methods in Java

You must have noticed the functions like main() and println() i.e. System.out.println, while studying Java applications. main() and println() are the already existing functions i.e. predefined in Java. But while designing your applications and applets, you can define your own functions or methods. These functions are called as user-defined functions . In Java functions are called as methods. Unlike other languages, Java has no stand-alone methods.

Why do we need user-defined methods ? 

It is possible to write all the code required for your program, without creating any user-defined methods. But it may result in the program becoming too large and complex as a result of which testing, debugging and maintaining the program may become a difficult task. But if a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These sub programs are also called as methods and they make the program easier to understand and debug. By using methods / methods, it saves time and memory space. 

Given below is an example of a Java program, in which a user-defined method findLargest, is used to find out the largest integer out of the four integers passed to it.

    public class Large  // Large is the name of the class
    {
        public static void main(String args[])
        {
            int num1, num2, num3, num4;
            int largest;  
            
            /* This statement defines L1, which is an instance or object 
               of class Large */
            Large L1; 
            
            /* This statement creates L1, which is an instance or object 
               of class Large */ 
            L1 = new Large( ); 
            
            /* assigning the values to the integer variables */
            num1 = 20;
            num2 = 36;
            num3 = 90;
            num4 = 110;  
            /* The integer variables num1,num2,num3,num4 are passed to 
               the function findLargest.  findLargest function finds out 
               the largest of the four integer numbers passed to it and 
               returns the largest integer, which is then assigned to the 
               variable largest */
            largest = L1.findLargest(num1, num2, num3, num4);  
            
            /* displays the largest integer */
            System.out.println("Largest number is   :  "+largest);
  
        }  /* main( ) function ends here */  

        /* Given below is the definition of function findLargest */  
        /*function header */
        int findLargest(int a,int b,int c,int d)     
        {
            /* function body */  
            /* to find out if a is the largest of the four integers */
            if(a > b && a > c && a > d)  
            {  
                /* if a is the largest of the four integers, then a is 
                   returned */
                return a;  
            }  
            /* if a is not largest of the four integers, it is checked 
               whether b is the largest of the four integers */
            else if(b > c && b > d) 
            {  
                /* if b is the largest of the four integers, then b is 
                   returned */
                return b;  
            }  
            /* if neither a nor b is the largest of the four integers, it 
               is checked whether c is the largest of the four integers */
            else if(c > d) 
            {  
                /* if c is the largest of the four integers, then c is 
                   returned */
                return c; 
            }
            else
            {
                return d;
            }
        } /* function findLargest ends here */
    } /* class Large ends here */

Method Definition

In Java functions are called as methods. Methods are functionally similar to the methods in C and C++.  They provide a way to group a block of code together and then refer to it by name. You can use the block of code again simply by referring to the name of the method.

How to define methods?

Now we will take a look at method definition of the method findLargest.

    int findLargest(int a, int b, int c, int d)
    {
        if (a > b && a > c && a > d)
        {  
            return a;
        }  
        else if( b > c && b > d)  
        {  
            return b;  
        }  
        else if(c > d)  
        {  
            return c;  
        }  
        else  
        {  
            return d;  
        }  
    }

Method definition consists of four parts:
  1. Name of the method
  2. Type of object or primitive type the method returns
  3. A list of parameters
  4. The body of the method

Name of the method, type of the object or the primitive data type the method returns and list of parameters constitute the method's signature or prototype.  It contains the most important information about the method itself.

In the function findLargest,
  1. Name of the method or function is findLargest
  2. Type of the data returned by the function is int data type.
  3. List of parameters passed to the function findLargest are num1, num2, num3, num4
  4. Rest everything between curly braces i.e. { and } is the body of the method

Unlike other languages, in Java you cannot distinguish a method from the other methods just by the name of the method. In Java you can have different methods that have the same name but a different argument list. This is called as method overloading. The syntax of method definition is:

    returntype methodname (parameter list)
    {
    ...........     //  body of the method
    ...........
    }

returntype is the type of the value, the method will return. It can be one of the primitive types, a class name or void if the method does not return a value at all.

Parameter list contains the types and names of arguments that must be passed to the method.  For example,   

    int findLargest(int num1, int num2, int num3, int num4)

Each parameter must be declared independently inside the parentheses. For example,

    int findLargest(int num1, num2, num3, num4)  // this is an invalid declaration  

The method's parameter list is a set of variable declarations, separated by commas, inside parentheses. These parameters become local variables in the body of the method, whose value is the value passed in when the method is called.  Inside the body of the method, you can have statements, expressions, method calls to other objects, conditional statements and loops.

Return 

If the method has to return a value (i.e. it has not been declared to return a void) somewhere inside the body of the method, you need to explicitly return a value. For this return keyword is used.  In the findLargest method, out of the four integer numbers, the largest integer number is returned.  Methods in Java can return any valid Java type.  This can be simple boolean, an array or an object.

Calling a Method in Java

In the example given above, findLargest method is called from the main() method. The statement given below calls the findLargest method from the main() method

    Largest = L1.findLargest(num1, num2, num3, num4);

Java does not support any stand-alone methods. The methods are defined and stored in a class.  To call a particular method, object of the class in which that method is stored has to be used to call that method. The syntax for calling a method in Java is:

    objectName.methodName(arg1, arg2, arg3.......);

objectName is the name of the object of the class in which the method is defined.

methodName is the name of the method that has to be called.

NOTE: All calls to methods must have parentheses after them, even if that method takes no arguments i.e. objectName.methodName( );

In the above example, the statement given below calls the findLargest method.

    Largest = L1.findLargest(num1, num2, num3, num4);

In this statement L1 is the object name which is an instance of class Large. The statement

    L1.findLargest(num1, num2, num3, num4);

calls the function findLargest. The findLargest method gets executed and returns the largest number out of the four numbers passed as parameter. The largest number returned by findLargest is then assigned to the integer variable Largest.

NOTE: The statement L1 = new Large(); creates an object or instance of class Large.

new operator is used for creating an instance of a given class and assigns memory space to it. 

Actual arguments or parameters: The arguments passed to a method while calling the method are called as actual arguments.  In the above example, while calling the method findLargest:

    L1.findLargest(num1, num2, num3, num4);

num1, num2, num3 and num4 are passed to the findLargest method. These arguments are called as actual arguments.

Formal arguments or parameters: The actual parameters passed while calling a method become the values of the formal parameters inside the called method. In the above example, when the findLargest method is called,

    L1.findLargest(num1, num2, num3, num4);

The actual arguments i.e. num1, num2, num3 and num4 are passed to the findLargest method.

In the findLargest method, the actual arguments i.e. num1, num2, num3 and num4 become a, b, c, d respectively. These are now called as formal arguments or parameters.

    int findLargest(int a,int b,int c,int d)
    {
    }

NOTE: The actual and formal parameters should match in number, type and order. The values of actual parameters are assigned to formal parameters on a one to one basis starting with the first parameter. The actual and formal parameters can have same name also i.e. in the above example, the actual parameters passed to findLargest method and the formal parameters inside the findLargest.

Function call                

    L1.findLargest(num1, num2, num3, num4);

Function definition                

    int findLargest(int num1, int num2, int num3, int num4)
    {
        .................
    }  

Passing arguments to methods

Whenever you call a method, object parameters are passed to the method by reference, whereas parameters of primitive data types are passed by value.

Passing the parameters to methods by value

When parameters are passed by value to a method, only a copy of the values of the actual arguments is passed into the called function. This means that whatever occurs to these variables inside the function, will have no effect on the variables used in the actual argument list.  Given below is an example of what happens when variables are passed by value:

    public class swap
    {
        public static void main(String args[])
        {
            int a, b;
            /* s1 is an object or instance of class swap */
            swap s1;  
            
            /* s1 is created here */  
            s1 = new swap(); 
            
            a = 10;
            b = 20;
            
            System.out.println("Value of a is "+a); /* value of a is 10 */
            System.out.println("Value of b is "+b); /* value of b is 20 */
            
            /* function swapping is called here, in which integer 
               arguments a and b are passed */ 
            s1.swapping(a, b);   
            
            /* after swapping function has executed, value of a still 
               remains 10 */
            System.out.println("When the swapping function has been executed, Value of a is "+a); 
            
            /* after swapping function has executed, value of b still 
               remains 20 */
            System.out.println("When the swapping function has been executed, Value of b is "+b); 
        }/* main method ends here */
        
        void swapping(int a, int b)
        {  
            /* temp variable will be used to swap the  values of a and b */
            int temp;     
            
            /* value of a is assigned to temp */
            temp = a;     
            
            /* value of b is assigned to a */
            a = b;       
            
            /* value of temp  is assigned to b */    
            b = temp;    
            
            /* value of a is 20 */  
            System.out.println("After swappig Value of a is " + a);    
            
            /* value of b is 10 */
            System.out.println("After swapping Value of b is " + b);   
        } /* method swapping ends here and control goes back to main 
             function */
    } /* definition of class swap ends here */

In this example, two integer variables i.e. a and b are taken and they are assigned the value 10 and 20 respectively.  These variables are then passed to the method swapping.  In the swapping method, the value contained in these variables is swapped with the help of integer variable temp. Due to swapping, the value of a becomes 20 and value of b becomes 10. But the effect of swapping of the values is only in the method itself. When we display the values of a and b after executing the swapping method, in the main method itself, the value of a is still 10 and the value of b is still 20. The reason is that primitive data type arguments are passed by value to the function.

Passing the parameters to methods by reference

When an object is passed as a parameter to a method, you are actually passing reference to that object rather than passing the object itself or the copy of the object. This means that whatever you do to those objects inside the method, will affect the original object as well. Given below is an example of passing by reference:

    class Rectangle /* class Rectangle is defined here */
    {  
        /* length and width are the member variables of class Rectangle */ 
        int length, width;  
        
        /* constructor of class Rectangle, which assigns the value to the 
           member variables */
        Rectangle(int x, int y) 
        {  
            /* values assigned to the member variables length and width */
            length = x;  
            width = y;
        }
    }/* class Rectangle definition ends here */

    /* Class RectangleArea, which contains the main method begins here */
    class RectangleArea 
    {  
        /* main method */
        public static void main(String args[]) 
        {  
            /* rect1 is an instance or object of class Rectangle, 15 and 
               10 are the values passed to the constructor of the object 
               rect1 */
            Rectangle rect1 = new Rectangle(15, 10);
            
            /* rect2 is an instance or object of class Rectangle, 30 and 
               23 are the values passed to the constructor of the object 
               rect2 */ 
            Rectangle rect2 = new Rectangle(30, 23);  
            /* r1 is an instance or object of class RectangleArea */  
            RectangleArea r1 = new RectangleArea( );  
            /* length and width of rect1 is displayed */
            System.out.println("length of rect 1 is " + rect1.length + "width is " + rect1.width); 
            
            /* length and width of rect2 is displayed */
            System.out.println("length of rect2 is " + rect2.length + "width is " + rect2.width); 
            
            /* method Swap is called here, to which objects of class 
               Rectangle i.e. rect1 and rect2 are passed */ 
            r1.Swap(rect1, rect2);  
            
            /* length and width of rect1 is displayed after the Swap 
               method*/
            System.out.println("length of rect 1 is " + rect1.length + "width is " + rect1.width);  
            
            /* length and width of rect2 is displayed  after the Swap 
               method */
            System.out.println("length of rect2 is " + rect2.length + "width is " + rect2.width);
        }
        void Swap(Rectangle rect1, Rectangle rect2)
        /* definition of Swap method */
        {
            int temp, temp1;  
            
            /*  length of rect1 is swapped with length of rect2 */
            temp = rect2.length;
            rect2.length = rect1.length;
            rect1.length = temp;
            
            /*  width of rect1 is swapped with width of rect2 */ 
            temp1 = rect2.width;
            rect2.width = rect1.width;
            rect1.width = temp1;
        }
    }

In the above example, we have defined two classes i.e. class Rectangle and class RectangleArea. As class RectangleArea contains the main method, so the name of this Java program will be RectangleArea.java. In the class RectangleArea, rect1 and rect2 are two objects of class Rectangle.  When the object rect1 is created, two integer values i.e. 15 and 10 are passed to it, which are assigned to the member variables i.e. length and width respectively through constructor function. Similarly when the object rect2 is created, again two integer values i.e. 30 and 23 are passed to it, which are assigned to the member variables i.e. length and width respectively through constructor function. Value of length and width of variables of rect1 and rect2 are displayed. Then Swap method is called, to which objects of class Rectangle i.e. rect1 and rect2 are passed. In Java, if objects are passed as parameters to the methods, then they are always passed by reference and not by value. The Swap method is defined to explain this aspect of the Java language.  In the Swap method, the length of rect1 is swapped with length of rect2 with the help of variable temp. The width of rect1 is swapped with the width of rect2 with the help of variable temp1. When the Swap method has executed, the program control returns back to the main method.  Again the values of the member variables i.e. length and width of rect1 and rect2 are displayed. Before Swap method was called, length of rect1 was 15 and length of rect2 was 30.  After Swap method has executed, length of rect1 becomes 30 and length of rect2 becomes 15. Before Swap method was called, width of rect1 was 10 and width of rect2 was 23. After Swap method has executed, the width of rect1 becomes 23 and width of rect2 becomes 10.


Comments