See the Tutorial List

Methods and Method Overloading in Java

In this tutorial we will learn how we can define class methods and make our classes more functional. And we will also learn about the concept of method overloading in Java.


Class Methods in Java

Methods describe behavior of an object. A method is a collection of statements that are grouped together to perform an operation.

For example, if we have a class Human, then this class should have methods like eating(), walking(), talking() etc, which in a way describes the behaviour which the object of this class will have.

Syntax:

return-type methodName(parameter-list)
{
 //body of method
}


Example of a Method:

public String getName(String st)
{
 String name="StudyTonight";
 name=name+st;
 return name;
}

method definition in java

Modifier : Modifier are access type of method. We will discuss it in detail later.

Return Type : A method may return value. Data type of value return by a method is declare in method heading.

Method name : Actual name of the method.

Parameter : Value passed to a method.

Method body : collection of statement that defines what method does.


Default Methods

In Java, Before Java 8 Version an Interface can have only abstract methods and the implementation of these methods has to be done in a separate class. To overcome this problem, Java 8 introduces a new concept of default methods. Default Methods allow an interface to have a method and also its implementation. It does not affect the classes which implement the interface.

Example:

  
interface Demo
{ 
    public void add(int p, int q); 
    default void print() 
    { 
System.out.println("Execution of Default Method"); 
    } 
}  
class DefaultDemo1 implements Demo
{ 
    public void add(int p, int q) 
    { 
int r = p + q;
  System.out.println("Total = "+r); 
    } 

    public static void main(String args[]) 
    { 
        DefaultDemo1 obj = new DefaultDemo1(); 
obj.add(10,20);  
obj.print(); 
    } 
}
  

default-method

Below is an Example of Default Method and Multiple Inheritance

Example:

  
interface Demo_A
{ 
    default void print_X() 
    { 
System.out.println("This is Demo_A Default Method"); 
    } 
} 
interface Demo_B
{ 
    default void print_X() 
    { 
System.out.println("This is Demo_B Default Method"); 
    } 
}  
class DefaultDemo2 implements Demo_A, Demo_B
{ 
    public void print_X() 
    {
Demo_A.super.print_X(); 
Demo_B.super.print_X(); 
    } 

    public static void main(String args[]) 
    { 
        DefaultDemo2 obj = new DefaultDemo2(); 
obj.print_X(); 
    } 
}
  

default-method


Returning Multiple values

In Java, Returning Multiple values is not supported. For returning multiple values following are the solution.

Below is an example in which we return an array.

Example:

  
class MethodDemo2{ 
    static int[] total(int a, int b) 
    { 
int[] s = new int[2]; 
s[0] = a + b; 
s[1] = a - b; 
        return s; 
    } 

    public static void main(String[] args) 
    { 
int[] s = total(200, 70); 
System.out.println("Addition = " + s[0]); 
System.out.println("Subtraction = " + s[1]); 
    } 
}
  

return-multiple-values

Below is an example in which Pare is used from javafx class.

Example:

  
import javafx.util.Pair; 
class MethodDemo3{ 
    public static Pair<Integer, String>b() 
    { 
        return new Pair<Integer, String>(22, "studytonight.com"); 
    } 
    public static void main(String[] args) 
    { 
        Pair<Integer, String>obj = b(); 
System.out.println(obj.getKey() + " " + obj.getValue()); 
    } 
}
  

return-multiple-values

Below is an example when there is more than two value to return.

Example:

  
class Demo{
int a; 
    double b; 
int c; 
Demo(int m, double d, int a) 
    { 
        a = m; 
        b = d; 
        c = a; 
    } 
} 
class MethodDemo4{ 
    static Demo get(int x, int y) 
    { 
        return new Demo(x * y, (double)x / y, (x + y)); 
    } 
    public static void main(String[] args) 
    { 
        Demo ans = get(25, 5); 
System.out.println("Multiplication = " + ans.a); 
System.out.println("Division = " + ans.b); 
System.out.println("Addition = " + ans.c); 
    } 
}
  

return-multiple-values


Parameter Vs. Argument in a Method

While talking about method, it is important to know the difference between two terms parameter and argument.

Parameter is variable defined by a method that receives value when the method is called. Parameter are always local to the method they dont have scope outside the method. While argument is a value that is passed to a method when it is called.

parameter and argument


call-by-value and call-by-reference

There are two ways to pass an argument to a method

  1. call-by-value : In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments.
  2. call-by-reference : In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.

NOTE :There is only call by value in java, not call by reference.


Example of call-by-value

public class Test
{
    public void callByValue(int x)
    {
        x=100;
    }
    public static void main(String[] args)
    {
       int x=50;
        Test t = new Test();
        t.callByValue(x);	//function call
        System.out.println(x);
    }

}

50


Parameter Passing

In Java, there is two way to pass the parameter i.e actual and formal argument. For example, there are two functions X() and Y(). If Y() calls X() then X() is called caller function and Y() is called called function. The argument which is sent by X() to Y() is called the actual argument and the parameters of Y() is called a formal argument.

Syntax for Formal Parameter

Function_name(datatype variable_name)

Function_name(datatype variable_name)

func_name(variable name(s));

parameter-passing-in-methods

Method Overloading in Java

If two or more method in a class have same name but different parameters, it is known as method overloading. Overloading always occur in the same class(unlike method overriding).

Method overloading is one of the ways through which java supports polymorphism. Method overloading can be done by changing number of arguments or by changing the data type of arguments. If two or more method have same name and same parameter list but differs in return type are not said to be overloaded method

Note: Overloaded method can have different access modifiers.


Different ways of Method overloading

There are two different ways of method overloading

Method overloading by changing data type of Arguments

For Example:

class Calculate
{
  void sum (int a, int b)
  {
    System.out.println("sum is"+(a+b)) ;
  }
  void sum (float a, float b)
  {
    System.out.println("sum is"+(a+b));
  }
  Public static void main (String[] args)
  {
    Calculate  cal = new Calculate();
    cal.sum (8,5);      //sum(int a, int b) is method is called.
    cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
  }
}

Sum is 13 Sum is 8.4

You can see that sum() method is overloaded two times. The first takes two integer arguments, the second takes two float arguments.


Method overloading by changing no. of argument.

For Example:

class Area
{
  void find(int l, int b)
  {
    System.out.println("Area is"+(l*b)) ;
  }
  void find(int l, int b,int h)
  {
    System.out.println("Area is"+(l*b*h));
  }
  public static void main (String[] args)
  {
    Area  ar = new Area();
    ar.find(8,5);   //find(int l, int b) is method is called
    ar.find(4,6,2);   //find(int l, int b,int h) is called
  }
}

Area is 40 Area is 48

In this example the find() method is overloaded twice. The first takes two arguments to calculate area, and the second takes three arguments to calculate area.

When an overloaded method is called java look for match between the arguments to call the method and the method's parameters. This match need not always be exact, sometime when exact match is not found, Java automatic type conversion plays a vital role.


Example of Method overloading with type promotion.

class Area
{
 void find(long l,long b)
 {
  System.out.println("Area is"+(l*b)) ;
 }
 void find(int l, int b,int h)
 {
  System.out.println("Area is"+(l*b*h));
 }
 public static void main (String[] args)
 {
  Area  ar = new Area();
  ar.find(8,5);     //automatic type conversion from find(int,int) to find(long,long) .
  ar.find(2,4,6)    //find(int l, int b,int h) is called.
 }
}

Area is 40 Area is 48

Below is an example in which the number of parameters is different.

Example:

  
import java.io.*;  
class Demo
{     
    public intsub(int p, int q)
    { 
int s = p - q; 
        return s; 
    } 
    public intadd(int x, int y, int z)
    { 
int s = x+y+z; 
        return s; 
    } 
} 
class MethodDemo8{ 
    public static void main (String[] args) { 
        Demo obj = new Demo(); 
int sum1 = obj.sub(20,5); 
System.out.println("Subtraction: " + sum1); 
int sum2 = obj.add(5,5,5); 
System.out.println("Addition :" + sum2); 

    } 
}
  

parameter-different-method-overloading

Below is an example in which the data type of parameters is different.

Example:

  
import java.io.*;  
class Demo
{     
    public intsub(int p, int q, int r)
    { 
int s = p + q + r; 
        return s; 
    } 

    public intadd(double x, double y, double z)
    { 
        double s = x + y + z; 
        return s; 
    } 
} 
class MethodDemo8{ 
    public static void main (String[] args) { 
        Demo obj = new Demo(); 
int sum1 = obj.sub(20,5,4); 
System.out.println("Subtraction: " + sum1); 
        double sum2 = obj.add(13.0, 2.0, 25.0); 
System.out.println("Addition :" + sum2); 

    } 
}
  

parameter-different-method-overloading

Below is an example in which the order of parameters is changed.

Example:

  
import java.io.*;  
class Demo{

    public void get(String name,  int id)
   { 
System.out.println("Company Name :"+ name);
  System.out.println("Company Id :"+ id); 
    } 

    public void get(int id, String name)
   { 
System.out.println("Company Id :"+ id); 
  System.out.println("Company Name :"+ name);
    } 
} 

class MethodDemo8{ 
    public static void main (String[] args) { 
  Demo obj = new Demo();
  obj.get("Cherry", 1);
  obj.get("Jhon", 2);
    } 
}
  

parameter-different-method-overloading


Overloading main()

In Java, we can overload the main() method using different number and types of parameter. But the JVM only understand the original main() method.

In Java, we can overload the main() method using different number and types of parameter. But the JVM only understand the original main() method.

Example:

  
public class MethodDemo10{ 
    public static void main(intargs) 
    { 
System.out.println("Main Method with int argument Executing"); 
    } 
    public static void main(char args) 
    { 
System.out.println("Main Method with char argument Executing"); 
    } 
    public static void main(Double[] args) 
    { 
System.out.println("Main Method with Double Executing"); 
    } 
    public static void main(String[] args) 
    { 
System.out.println("Original main Executing"); 
    } 
}
  

overloading-main

In the above example as we have seen that whenever the overloaded main method is called always the original main method was invoked. To solve this problem below is an example.

Example:

  
public class MethodDemo10{ 
    public static void main(intargs) 
    { 
System.out.println("Main Method with int argument Executing"); 
  System.out.println(args);
    } 
    public static void main(char args) 
    { 
System.out.println("Main Method with char argument Executing");
  System.out.println(args); 
    } 
    public static void main(Double[] args) 
    { 
System.out.println("Main Method with Double Executing"); 
  System.out.println(args);
    } 
    public static void main(String[] args) 
    { 
System.out.println("Original main Executing"); 
  MethodDemo10.main(12);
  MethodDemo10.main('c');
  MethodDemo10.main(1236);
    } 
}
  

overloading-main


Method overloading and null error

Below is an example in which you will know how a null value can cause an error when methods are overloaded.

Example:

  
public class MethodDemo9 
{ 
    public void test(Integer i) 
    { 
System.out.println("test(Integer ) "); 
    } 
    public void test(String name) 
    { 
System.out.println("test(String ) "); 
    } 
    public static void main(String [] args) 
    { 
        Demo obj = new Demo();  
obj.test(null); 
    } 
}
  

method-overloading-null-error

Reason:

The main reason for getting the compile time error in the above example is that here we have Integer and String as arguments which are not primitive data types in java and this type of argument do not accept any null value. When the null value is passed the compiler gets confused which method is to be selected as both the methods in the above example are accepting null.

Below is the example in which the above problem is solved.

Example:

   
public class MethodDemo9 
{ 
    public void test(Integer i) 
    { 
System.out.println("Method ==> test(Integer)"); 
    } 
    public void test(String name) 
    { 
System.out.println("Method ==> test(String) "); 
    } 
    public static void main(String [] args) 
    { 
        MethodDemo9 obj = new MethodDemo9 ();  
  Integer a = null;
obj.test(a);
  String b = null;
obj.test(b); 
    } 
}
   

method-overloading-null-error