Method Overloading with Different Return Types in Java


Write a Java program to demonstrate method overloading with different return types

The Java class MathUtil exemplifies the concept of method overloading, a feature that enables multiple methods within a class to share the same name but differ in their parameter types or number of parameters. In this case, the add method is overloaded to accommodate addition operations for both integers and doubles. The first add method accepts two integer parameters and returns their sum as an integer, while the second add method takes two double parameters and returns their sum as a double.

Within the main method, an instance of MathUtil is instantiated, and method calls are made to the add method with different argument types: integer arguments for the first call and double arguments for the second call. The results of these method calls are printed to the console, illustrating the respective sums of the integer and double values. This demonstrates how method overloading enhances code readability and reusability by allowing the same method name to be used for similar operations on different data types.

Source Code

class MathUtil
{
	int add(int a, int b)
	{
		return a + b;
	}
 
	double add(double a, double b)
	{
		return a + b;
	}
 
	public static void main(String[] args)
	{
		MathUtil math = new MathUtil();
		System.out.println("Sum of Two Integers : " + math.add(5, 3));
		System.out.println("Sum of Two Doubles : " + math.add(5.5, 3.3));
	}
}

Output

Sum of Two Integers : 8
Sum of Two Doubles : 8.8

Example Programs