Method Overloading with Overloaded Methods That Use Different Types of Arrays as Parameters in Java


Create a Java program to demonstrate method overloading with overloaded methods that use different types of arrays as parameters

  • The Calculator class contains two sumArray methods, each accepting an array of numbers, either int[] or Integer[].
  • The first sumArray method accepts an array of primitive int numbers, and the second one accepts an array of Integer objects.
  • Both methods calculate the sum of the elements in the array and return the result.
  • In the Main class, an instance of Calculator is created.
  • Two arrays, arr1 and arr2, are initialized with integer values.
  • The sumArray method is called twice, once with arr1 and once with arr2.
  • The appropriate sumArray method is invoked based on the type of the array passed (primitive int[] or Integer[]), and the sum of the elements in each array is printed.

Source Code

class Calculator
{
	int sumArray(int[] numbers)
	{
		int sum = 0;
		for (int num : numbers)
		{
			sum += num;
		}
		return sum;
	}
 
	int sumArray(Integer[] numbers)
	{
		int sum = 0;
		for (Integer num : numbers)
		{
			sum += num;
		}
		return sum;
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Calculator calculator = new Calculator();
		int[] arr1 = {1, 2, 3, 4, 5};
		Integer[] arr2 = {2, 4, 6, 8, 10};
		System.out.println("Sum of Int Array : " + calculator.sumArray(arr1));
		System.out.println("Sum of Integer Array : " + calculator.sumArray(arr2));
	}
}

Output

Sum of Int Array : 15
Sum of Integer Array : 30

Example Programs