Method in Java

Methods appear inside class bodies. They contain local variable declarations and other Java statements that are executed when the method is invoked. Methods may return a value to the caller. They always specify a return type, which can be a primitive type, a reference type, or the type void , which indicates no returned value. Methods may take arguments, which are values supplied by the caller of the method. Lets see example:

Program


class multiply
{
    int num1;
    int num2;
    int mul(int x,int y)
    {
        int result;
        num1 = x;
        num2 = y;
        result = num1*num2;
        return result;
    }
}

public class Main
{
    public static void main (String[] args) 
    {
        multiply m = new multiply();
        System.out.println("multiplication of 3 and 5 is " + m.mul(3,5));
    }
}
  
  

Output


multiplication of 3 and 5 is 15
  

Explanation

In this example, the class multiply defines a method, mul(), that takes as arguments two integers: x and y. It returns a int type value as a result, using the return keyword. Our method has a fixed number of arguments (two); however, methods can have variable-length argument lists, which allow the method to specify that it can take any number of arguments and sort them itself at runtime.

Local variables

Our mul() method declares a local variable called result, which it uses to compute the multiplication of two numbers. A local variable is temporary; it exists only within the scope (the block) of its method. Local variables are allocated when a method is invoked; they are normally destroyed when the method returns. They can’t be referenced from outside the method itself. If the method is executing concurrently in different threads, each thread has its own version of the method’s local variables. A method’s arguments also serve as local variables within the scope of the method; the only difference is that they are initialized by being passed in from the caller of the method.

A varibale created within a method and assigned to a local variable may or may not persist after the method has returned. As with all variable in Java, it depends on whether any references to the variable remain. If an variable is created, assigned to a local variable, and never used anywhere else, that variable is no longer referenced when the local variable disappears from scope, so garbage collection removes the variable. If, however, we assign the variable to an instance variable of an object, pass it as an argument to another method, or pass it back as a return value, it may be saved by another variable holding its reference.

Difference between local variable and instance variable

Now let's see the difference between instance variable and local variable. local variables are local in scope and they are not visible or accessible outside there scope which is determined by {} while instance variables are visible on all part of code based on there access modifier e.g. public , private or protected. The only public can be accessed from outside while protected and private can be accessed from subclass and class itself. Access modifier can not be applied to a local variable and you can not even make them static. The only modifier which is applicable to a local variable is final and only final local variables are visible inside the anonymous class. the value of instance variable is limited to an instance, one instance can not access the value of other instance in Java.

Shadowing of instance variable by local variable

If a local variable and an instance variable have the same name, the local variable shadows or hides the name of the instance variable within the scope of the method. In the following example, the local variables num1 and num2 hide the instance variables of the same name:

Program


class multiply
{
    //instance variable
    int num1;
    int num2;
    int mul(int x,int y)
    {
        //local variable
        int result;
        //assigning x and y to local variable 
        int num1 = x;
        int num2 = y;
        result = num1*num2;
        return result;
    }
}

public class Main
{
    public static void main (String[] args) 
    {
        multiply m = new multiply();
        System.out.println("multiplication of 3 and 5 is " + m.mul(5,3));
        //we have assigned x and y to local variable so we can't access the value of x and y outside method
        System.out.println("num1 = " + m.num1 + " num2 = " + m.num2);
    }
}
  
  

Output


multiplication of 3 and 5 is 15
num1 = 0 num2 = 0
  

Explanation

When we set the values of the local variables in mul(), it has no effect on the values of the instance variables.So they are zero.So, this is also example of a varibale created within a method and assigned to a local variable may or may not persist after the method has returned. As with all variable in Java, it depends on whether any references to the variable remain.

Now lets see the example without shadowing.

Program


class multiply
{
    //instance variable
    int num1;
    int num2;
    int mul(int x,int y)
    {
        //local variable
        int result;
        //assigning x and y to instance variable 
        num1 = x;
        num2 = y;
        result = num1*num2;
        return result;
    }
}

public class Main
{
    public static void main (String[] args) 
    {
        multiply m = new multiply();
        System.out.println("multiplication of 3 and 5 is " + m.mul(5,3));
        //we have assigned x and y to instance variable so we can access the value of x and y outside method
        System.out.println("num1 = " + m.num1 + " num2 = " + m.num2);
    }
}
  
  

Output


multiplication of 3 and 5 is 15
num1 = 5 num2 = 3
  

Explanation

Like I said- If, however, we assign the variable to an instance variable of an object, pass it as an argument to another method, or pass it back as a return value, it may be saved by another variable holding its reference.

Method overloading

Method overloading is the ability to define multiple methods with the same name in a class; when the method is invoked, the compiler picks the correct one based on the arguments passed to the method. This implies that overloaded methods must have different numbers or types of arguments.

Method overloading (also called ad-hoc polymorphism ) is a powerful and useful feature. The idea is to create methods that act in the same way on different types of arguments. This creates the illusion that a single method can operate on many types of arguments. The print() method in the standard PrintStream class is a good example of method overloading in action. As you’ve probably deduced by now, you can print a string representation of just about anything using this expression:

System.out.print( argument );
  
The variable out is a reference to an object (a PrintStream) that defines nine different, “overloaded” versions of the print() method. The versions take arguments of the following types: Object, String, char[], char, int, long, float, double, and boolean.

You can invoke the print() method with any of these types as an argument, and it’s printed in an appropriate way. In a language without method overloading, this requires something more cumbersome, such as a uniquely named method for printing each type of object. In that case, it’s your responsibility to figure out what method to use for each data type.

What if there’s more than one possible match? For example, we try to print a subclass of String called MyString. (The String class is final so it can’t really be subclassed, but let’s use our imaginations.) MyString is assignable to either String or to Object. Here, the compiler makes a determination as to which match is “better” and selects that method. In this case, it’s the String method.

The intuitive explanation for this is that the String class is "closer" to MyString in the inheritance hierarchy. It is a more specific match. A slightly more rigorous way of specifying it would be to say that a given method is more specific than another method if the argument types of the first method are all assignable to the argument types of the second method. In this case, the String method is more specific to a subclass of String than the Object method because type String is assignable to type Object. The reverse is not true.

Method overloading is not something that happens at runtime; this is an important distinction. It means that the selected method is chosen once, when the code is compiled. Once the overloaded method is selected, the choice is fixed until the code is recompiled.

Example of method overloading with changing no of arguments

Program


class SUM
{  
    //two arguments
    int add(int a, int b)
    {
        return a+b;
    }  
    //three arguments
    int add(int a,int b,int c)
    {
        return a+b+c;
    }  
}  
class Main{  
    public static void main(String[] args)
    {  
        SUM s = new SUM();
        System.out.println(s.add(11,12));  
        System.out.println(s.add(12,1,15));  
    }
}  
  
  

Output


23
28
  

Explanation

In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.

Example of method overloading with changing data type of arguments

Program


class SUM
{  
    //int argument
    int add(int a, int b)
    {
        return a+b;
    }  
    //double argument
    double add(double a, double b)
    {
        return a+b;
    }  
}  
class Main{  
    public static void main(String[] args)
    {  
        SUM s = new SUM();
        System.out.println(s.add(11,12));  
        System.out.println(s.add(12.3,1.6));  
    }
}  
  
  

Output


23
13.9
  

Explanation

In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.

Comments

Popular posts from this blog

System.Environment

System.Console

Datatype and keyword