×

Java Programs

Java Practice

Java program to implement method overloading based on types of arguments

Learn how to implement method overloading based on types of arguments in Java?
Submitted by Nidhi, on March 22, 2022

Problem statement

In this program, we will create 3 methods with the same name but all methods have different types of arguments to calculate the sum of given arguments.

Source Code

The source code to implement method overloading based on types of arguments is given below. The given program is compiled and executed successfully.

// Java program to implement method overloading based 
// on types of arguments

public class Main {
  static double sum(int num1, int num2) {
    float s = 0;
    s = num1 + num2;
    return s;
  }
  
  static double sum(int num1, float num2) {
    float 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);

    result = sum(30, 34.25);
    System.out.println("Sum : " + result);
  }
}

Output

Sum : 30.0
Sum : 40.55999755859375
Sum : 64.25

Explanation

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

The main() method is the entry point for the program, here we called overloaded methods and printed the result.

Java Method Overloading Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.