Table of Contents

Method Overloading is an essential concept in Java. It helps to increase the program’s readability.  Programmers can reduce the execution time and make the coding looks clean. Moreover, it provides flexibility. Let’s discuss in detail Method Overloading in Java with Example.

Method Overloading in java

Method Overloading in Java

In the same class, if we have many methods of the same name is called method overloading. However, it differs in the Number of arguments and type of arguments.

Images

Suppose, You want to add a given number. But the Number can be anything. In the case of adding two numbers, then

int a(int a, int b)
{
 int c;
 c=a+b;
 return c;
}

If you wish to add three integers, then

int b(int a, int b, int c)
{
  int d;
  d=a+b+c;
  return d;
}

b(int, int, int). While doing as above will create confusion. 

The operation’s name differs from its behavior, and the programmers need clarification. Overloading takes the place of solving the problem mentioned above. Therefore, Method Overloading increases the readability of the program.

int add(int a, int b)
{
 int c;
 c=a+b;
 return c;
}
int add(int a, int b, int c)
{
  int d;
  d=a+b+c;
  return d;
}

Two approaches in this illustration share the same name, “add,” but the number of arguments differs. It is how Method Overloading works.

Types of method overloading in Java

  1. Overloading a method by having a different number of arguments
  2. Overloading a method by having different datatypes of the arguments.
    1. By Overloading a method by changing the order of arguments.

1.Overloading a method by having a different number of arguments

It is one type of method overloading in Java. You can have two methods having the same name, but it differs by the Number of parameters they have.

Let’s see an example

class Addition{  
static int add(int a,int b)
{
return a+b;
}  
static int add(int a,int b,int c)
{
return a+b+c;
}  
}  
class OverloadingType1{  
public static void main(String[] args){  
System.out.println(Addition.add(11,11));  
System.out.println(Addition.add(11,11,11));  
}
}  

Output

22
33

Here, the class name is Addition. We have two methods with the same name as add in the same class. But the difference is in the first method, the number of parameters is 2. At the same time, the second method has three parameters.

In the main method, when the first statement executes, the control will go to the add method having two parameters. Similarly, when the second statement executes, control will go to the add method having 3  parameters. 

So, that is how the method overloading in Java with type 1 works

2. Overloading a method by having different datatype of the arguments

It is one type of method overloading in Java. You can have two methods having the same name, but it differs in the type of parameters they have.

Let’s see an example.

class Addition{  
static int add(int a, int b)
{
return a+b;
}  
static double add(double a, double b)
{
return a+b;
}  
}  
class OverloadingType2{  
public static void main(String[] args){  
System.out.println(Addition.add(11,11));  
System.out.println(Addition.add(12.3,12.6));  
}
}  

Output

22
24.9

Here, the class name is Addition. We have two methods with the same name as add in the same class. But the difference is in the first method. The type of parameter is an integer. At the same time, the second method has a double type.

In the main method, when the first statement executes, the control will go to the add method integer datatype. Similarly, when the second statement executes, control will go to the add method having datatype double. So, that is how the method overloading in Java with type 2 works.

3. Overloading a method by changing the order of arguments

For instance, if method 1’s arguments are (String name, int roll no) and method 2’s parameters are (int roll no, String name). Still, both methods have the same name, and then these two methods are seen to be overloaded with various parameter combinations.

class StudentDetails{  
    public void student(String name, int rollno)
    {
            System.out.println("Name :" + name + " " + "Roll No :" + rollno);
    }
    public void student(int rollno, String name)
    {
        System.out.println("RollNo :" + rollno + " " + "Name :" + name);
    }
}  
class OverloadingType3{  
public static void main(String[] args){  
StudentDetails obj = new StudentDetails();
obj.student("Sakthi", 1);
obj.student(2, "Nivetha");
}
}  

Output

Name: Sakthi Roll No :1

Roll No:2 Name: Nivetha

method overloading in java

What happens if the accurate prototype conflicts with the arguments?

Before going to the answer to this question, we should learn a little about type conversion in Java. Let’s check with type conversion.Like other languages, Java has a variety of data types.

They are boolean, char, int, unsigned int, signed int, float, double, and long. Hence, for seven types, each of which requires a different amount of memory space to store.

The two data types may not be compatible when you assign one value to the other. The data types should be compatible with Java to convert them automatically. It is known as Automatic Type Conversion.

Otherwise, they must be cast or explicitly converted, like Putting an int value into a long variable.

DatatypeBits Acquired In Memory

Datatypesize
boolean1
byte8 (1 byte)
char16 (2 bytes)
short16 (2 byte)
int32 (4 bytes)
long64 (8 bytes)
float32 (4 bytes)
double64 (8 bytes)

Automatic conversion takes place in two ways. They are:

  • Data types should be compatible.
  • A smaller data type’s value is transferred to a larger data type.

For instance, while Java’sJava’s numeric data types are compatible, automated translation to char or boolean is not supported. Moreover, char and boolean are incompatible.

Byte Short Int Long Float Double

Example

class AutoConversion{
public static void main(String[] args)
    {
        int i = 100;
        long l = i;
float f = l;
	System.out.println("Int value " + i);
        System.out.println("Long value " + l);
        System.out.println("Float value " + f);
    }
}

Output

Int value 100

Long value 100

Float value 100.0

Let’s now come to the answer, as mentioned earlier.

The compiler does the following in order of priority:

  • Type conversion, but to a higher type within the same family (in terms of range).
  • Changing a type to the following higher family
class Example{
    public void show(int x)
    {
        System.out.println("In int" + x);
    }
    public void show(String s)
    {
        System.out.println("In String" + s);
    }
    public void show(byte b)
    {
        System.out.println("In byte" + b);
    }
}
class ExampleMain {
    public static void main(String[] args)
    {
        byte a = 25;
        Example e = new Example();
  
         e.show(a);
         e.show("hello");
 	 e.show(250);
 	 e.show('A');
 	 e.show("A");
 	 e.show(7.5);
    }
}

Exceptions in Method Overloading in Java

We cannot overload a method by changing its return type

Because of ambiguity, method overloading in Java is impossible by modifying the method’s return type. Let’s look at some examples of ambiguity.

class Addition{  
static int add(int a,int b)
{
return a+b;
}  
static double add(int a,int b)
{
return a+b;
}  
}  
class OverloadingType4{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));//ambiguity  
}
}  

Output

Compile Time Error

Note: Run Time Error is preferable to Compile Time Error. So, if you declare the same method with the same parameters, the Java compiler generates a compile time error.

2. We cannot overload the main() method in Java

Through method overloading, yes. You can have many main methods. Yet, JVM invokes the main() function, which takes a string array as its single parameter. Here’s a clear illustration:

class OverloadingType5{  
public static void main(String[] args)
{
System.out.println("main with String[]");
}  
public static void main(String args)
{
System.out.println("main with String");
}  
public static void main()
{
System.out.println("main without args");
}  
}  

Output

main with String[]

3. Can we Overload static methods in Java?

The solution is “Yes.” Although they may have different input arguments, more than one static method with the same name are possible. Take the following Java program, for instance.

public class StaticMethodExample {
    public static void disp() {
        System.out.println("StaticMethodExample .disp() called ");
    }
    public static void disp(int a) {
        System.out.println("StaticMethodExample .disp(int) called ");
    }
    public static void main(String args[])
    {
        StaticMethodExample .disp();
        StaticMethodExample .disp(10);
    }
}

Output

StaticMethodExample .disp() called 

StaticMethodExample .disp(int) called

4. Can a method be overloaded when it differs only by static keywords?

If the two methods only differ by the static keyword, we cannot overload them if the number of parameters and types of parameters is the same.

public class ExampleStaticMethod{
    public static void disp() {
        System.out.println("ExampleStaticMethod.disp() called ");
    }
    public void disp() { // Compiler Error: cannot redefine foo()
        System.out.println("ExampleStaticMethod.disp(int) called ");
    }
    public static void main(String args[]) {
        ExampleStaticMethod.disp();
    }
}

Output

Compiler Error, cannot redefine disp()

Advantages of method overloading

  • Method overloading makes the code easier to read.
  • It makes our task much more straightforward by preventing us from having to memorize any exact names for the different types and numbers of parameters.
  • Method overloading makes it simpler to maintain the application.
  • For handling class objects, we can make effective use of overloaded methods.

Method Overloading in Java with Example

1. Find the Area of the Rectangle Using Method Overloading in Java

The rectangle’s Area is calculated by multiplying its length by width or breadth. The following formula can be used to determine the rectangle’s Area quickly:

rectangle Area = Length * Breath

import java.io.*;
 
class RectangleArea {
 
    void Area(double l, double b)
    {
        System.out.println("Area of the rectangle: "
                           + l * b);
    }
 
    void Area(int l, int b)
    {
        System.out.println("Area of the rectangle: "
                           + l * b);
    }
}
 
class MethodOverloadingExample{
 
public static void main(String[] args)
    {
 
       RectangleArea r= new RectangleArea();
 
        // Calling function
        r.Area(20, 10);
        r.Area(10.5, 5.5);
    }
}

Output

Area of the rectangle: 200

Area of the rectangle: 57.75

2. Find the Area of the circle Using the Method Overloading in Java

The Area of the circle is the square of the circle’s radius multiplied by PI’s value. The following formula can be used to determine the circle’s surface area quickly:

 circle Area: A = π * rad2

where rad is the radius

circle Area: A = (π / 4) * dia2

where dia is the diameter

 PI = 3.141592653589793.

Example 1:

import java.io.*;
 class CircleArea {
 static final double PI = Math.PI;
   void Area(double rad)
    {
        double A = PI * rad * rad;
        System.out.println("Circle area  is:" + A);
    }
  void Area(float rad)
    {
        double A = PI * rad * rad;
        System.out.println("Circle Area is:" + A);
    }
}
 class MethodOverloadingExample
{
  public static void main(String[] args)
    {
  CircleArea c= new CircleArea();
  c.Area(5);
  c.Area(2.5);
    }
}

Output

Circle Area is:78.53981633974483

Circle Area is:19.634954084936208

Example 2:

import java.io.*;
 class CircleArea {
 static final double PI = Math.PI;
  void Area(double D)
    {
        double A = (PI / 4) * D * D;
System.out.println("The area of the circle is:" + A);
    }
 
    void Area(float D)
    {
        double A = (PI / 4) * D * D;
   System.out.println("The area of the circle is:" + A);
    }
}
 
class MethodOverloadingExample{
 
       public static void main(String[] args)
    {
   CircleArea c= new CircleArea();
   c.Area(10);
        c.Area(20.4);
    }
}

Output

The Area of the circle is:78.53981633974483

The Area of the circle is:326.851299679482

3. Find the Area of the Square Using the Method Overloading in Java

The square’s Area equals the sum of its sides. The following formula can be used to determine the square’s Area quickly:

Area of the Square: A = s2

import java.io.*;
 class SquareArea {
     void Area(double side)
    {
        System.out.println("Area of the Square: "
                           + side * side);
    }
   void Area(float side)
    {
        System.out.println("Area of the Square: "
                           + side * side);
    }
}
 
class MethodOverloadingExample{
     public static void main(String[] args)
    {
         SquareArea s= new SquareArea();
         s.Area(10);
         s.Area(3.2);
    }
}

Output

Area of the Square: 100.0

Area of the Square: 10.240000000000002

4. Print Different Types of Array using method overloading in Java

class methodOverloadingDemo {
    public static void printArray(Integer[] arr)
    {
        System.out.println("\nThe Integer array is: ");
     for (Integer i : arr)
            System.out.print(i + " ");
        System.out.println();
    }
 
   public static void printArray(Character[] arr)
    {
        System.out.println("\nThe Character array is: ");
 
     for (Character i : arr)
            System.out.print(i + " ");
        System.out.println();
    }
 
    public static void printArray(String[] arr)
    {
        System.out.println("\nThe String array is: ");
 
        for (String i : arr)
            System.out.print(i + " ");
        System.out.println();
    }
 
    public static void printArray(Double[] arr)
    {
        System.out.println("\nThe Double array is: ");
 
            for (Double i : arr)
            System.out.print(i + " ");
    }
 
    public static void main(String args[])
    {
 Integer[] iarr = { 2, 12, 22, 32, 42 };
        Character[] carr = { 'W', 'E', 'L', 'C', 'O', 'M', 'E' };
        String[] sarr
            = { "Nivetha", "Iniya", "Sakthi", "Siva", "Madhu" };
        Double[] darr
            = { 42.3210, 91.321, 75.231, 28.543, 5.342 };
 
        printArray(iarr);
        printArray(carr);
        printArray(sarr);
        printArray(darr);
    }
}

Output

The Integer array is: 

2 12 22 32 42

The Character array is: 

W E L C O M E

The String array is: 

Nivetha Iniya Sakthi Siva Madhu

The Double array is: 

42.3210 91.321 75.231 28.543 5.342 

Online Java Training

Henry Harvin offers the JAVA Foundation the DS & Algo Combo Certification Course, which BestCourseNews.com has named the best Java certification course. With this course, which more than 160 top corporations endorse, you will be recognized as a Certified Java Developer and receive hands-on instruction with more than 350 coding challenges and 50+ Java tools. The website of Henry Harvin has more information on this program right now.

Henry Harvin provides Java Courses by professionals. Enroll now to learn more about Java Java Programming Course for Beginners

Recommended Reads

  1. Java Full Stack Developer Skills in 2023
  2. 40+ Core Java Interview Questions and Answers for Freshers and Experienced in 2023
  3. Top 20 Java Books for 2023
  4. Top 50+ OOPs Interview Questions and Answers in 2023

FAQS

1. What is method overloading in Java?

Method overloading is when the methods’ names are the same, but their parameters vary.

2. In Java, can static methods be overloaded?

Sure, static methods in Java can be overloaded, but they cannot be replaced.

3. Can the main method be overloaded?

Indeed, you can overload the main method in Java, but the JVM will only call the method with the signature public static void main(String[] args).

4. Can we alter the method overloading’s return type only?

No, If we merely alter the return type, the compiler will have trouble determining which method to call.

5. Describe the method signature. What components does it have?

The compiler uses the method signature to distinguish between the methods. There are three components to a method signature. They are the method’s name, Number of arguments, and Argument types.

6. Can methods that are overloaded be synchronized?

Yes. Methods that are overloaded can be synchronized.

7. Is it possible to make overloaded methods final?

Indeed, overloaded methods may be declared final.

Post Graduate Program And our courses

Ranks Amongst Top #5 Upskilling Courses of all time in 2021 by India Today

View Course
Career Advice

Join the Discussion

Interested in Henry Harvin Blog?
Get Course Membership Worth Rs 6000/-
For Free

Our Career Advisor will give you a call shortly

Someone from India

Just purchased a course

1 minutes ago
Henry Harvin Student's Reviews
Henry Harvin Reviews on Trustpilot | Henry Harvin Reviews on Ambitionbox |
Henry Harvin Reviews on Glassdoor| Henry Harvin Reviews on Coursereport