Method Overloading with Primitive Data Types and Their Wrapper Classes in Java


Create a Java program to demonstrate method overloading with primitive data types and their wrapper classes

This Java program demonstrates method overloading with primitives and their corresponding wrapper classes in a class named MethodOverloadingDemo.

  • In the main method, an instance of the MethodOverloadingDemo class is created.
  • Various add methods of MethodOverloadingDemo are called with different arguments.
  • The add method is overloaded to accept both primitive types (int and double) and their corresponding wrapper classes (Integer and Double).
  • When the method is called with primitive arguments, the method with primitive parameters is invoked.
  • When the method is called with wrapper class arguments, the method with wrapper class parameters is invoked.
  • The appropriate overloaded methods are called based on the arguments passed, and the results are printed to the console.

Source Code

public class OverloadingWithPrimitivesAndWrappersDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo calculator = new MethodOverloadingDemo();
 
		int intSum = calculator.add(5, 10);
		Integer integerSum = calculator.add(15, 20);
		double doubleSum = calculator.add(3.5, 4.5);
		Double doubleObjSum = calculator.add(7.5, 8.5);
 
		System.out.println("Sum of int : " + intSum);
		System.out.println("Sum of Integer : " + integerSum);
		System.out.println("Sum of double : " + doubleSum);
		System.out.println("Sum of Double : " + doubleObjSum);
	}
}
class MethodOverloadingDemo
{	
	int add(int a, int b)// Method to add two integers
	{
		return a + b;
	}
 
	Integer add(Integer a, Integer b)// Method to add two Integer objects
	{
		return a + b;
	}
 
	double add(double a, double b)// Method to add two doubles
	{
		return a + b;
	}
 
	Double add(Double a, Double b)// Method to add two Double objects
	{
		return a + b;
	}
}

Output

Sum of int : 15
Sum of Integer : 35
Sum of double : 8.0
Sum of Double : 16.0

Example Programs