Method Overloading with Overloaded Methods That Use Different Combinations of Parameter Modifiers Including Final and Varargs in Java


Create a Java program to demonstrate method overloading with overloaded methods that use different combinations of parameter modifiers, including final and varargs

  • In the main method of the OverloadingWithParameterModifiersAndVarargsDemo class, an instance of the MethodOverloadingDemo class is created.
  • Two variables message and number are initialized with a string and an integer value, respectively.
  • The printInfo method of the MethodOverloadingDemo class is called twice, once with a string argument and varargs and once with an integer argument, varargs, and strings.
  • The first call printer.printInfo(message, 1, 2, 3, 4, 5) invokes the method with a non-final parameter and varargs, and it prints the string message along with the varargs numbers.
  • The second call printer.printInfo(number, "How", "are", "you?") invokes the method with a final parameter and varargs, and it prints the integer number along with the varargs strings.

Source Code

public class OverloadingWithParameterModifiersAndVarargsDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo printer = new MethodOverloadingDemo();
 
		String message = "Hello World";
		int number = 67;
 
		printer.printInfo(message, 1, 2, 3, 4, 5);
		printer.printInfo(number, "How", "are", "you?");
	}
}
class MethodOverloadingDemo
{
	void printInfo(String message, int... numbers) // Method with a non-final parameter and varargs
	{
		System.out.println("Printing non-final with varargs : " + message);
		for (int num : numbers)
		{
			System.out.print(num + " ");
		}
		System.out.println();
	}
 
	void printInfo(final int number, String... messages) // Method with a final parameter and varargs
	{
		System.out.println("Printing final with varargs : " + number);
		for (String msg : messages)
		{
			System.out.print(msg + " ");
		}
		System.out.println();
	}
}

Output

Printing non-final with varargs : Hello World
1 2 3 4 5
Printing final with varargs : 67
How are you?

Example Programs