Method Overloading with Methods Having Varargs of Different Types in Java


Write a Java program to demonstrate method overloading with methods having varargs of different types

This Java program demonstrates method overloading in a class named DataPrinter, where there are two display methods: one to display string values and another to display integer values. Let's break down the code:

  • The main method creates an instance of the DataPrinter class.
  • It then calls the display methods with different arguments.
  • The Java compiler determines which overloaded method to call based on the number and type of arguments passed.
  • For each call to display, the appropriate version of the method is invoked, and the corresponding values are printed to the console.

Source Code

class DataPrinter
{
	void display(String... values)
	{
		System.out.println("String Values :");
		for (String value : values)
		{
			System.out.println(value);
		}
	}
 
	void display(int... values)
	{
		System.out.println("Integer Values :");
		for (int value : values)
		{
			System.out.println(value);
		}
	}
 
	public static void main(String[] args)
	{
		DataPrinter printer = new DataPrinter();
		printer.display("Java", "Exercise", "Programs");
		printer.display(1, 2, 3, 4, 5);
	}
}

Output

String Values :
Java
Exercise
Programs
Integer Values :
1
2
3
4
5

Example Programs