Learn how to implement method overloading based on type promotion in Java?
Submitted by Nidhi, on March 22, 2022

Problem Solution:

In this program, we will implement method overloading based on the different number of arguments but here we will demonstrate type promotion, here we will pass argument float type, but argument is defined of type double in the method signature.

Program/Source Code:

The source code to implement method overloading based on type promotion is given below. The given program is compiled and executed successfully.

```// Java program to implement method overloading
// based on type promotion

public class Main {
static double sum(int num1, int num2) {
double s = 0;
s = num1 + num2;
return s;
}

static double sum(int num1, double num2) {
double s = 0;
s = num1 + num2;
return s;
}

public static void main(String[] args) {
double result = 0;

result = sum(10, 20);
System.out.println("Sum : " + result);

result = sum(20, 20.56F);
System.out.println("Sum : " + result);
}
}
```

Output:

```Sum : 30.0
Sum : 40.55999946594238
```

Explanation:

In the above program, we created a Main class that contains a method main() and 2 overloaded method sum() to calculate the addition of specified arguments.

The main() method is the entry point for the program, here we passed the argument float type, but the argument is defined as type double in method signature using the below statement,

```result = sum(20, 20.56F);
```

What's New

Top Interview Coding Problems/Challenges!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates