Method Overloading with Different Parameter Types and Variable Arguments in Java


Create a Java program to demonstrate method overloading with different parameter types and variable arguments

This Java program demonstrates method overloading in a class named Printer, where there are two print methods: one to print a single string and another to print an integer followed by multiple string messages. Let's break down the code:

  • The main method creates an instance of the Printer class.
  • It then calls the print 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 print, the appropriate version of the method is invoked, and the corresponding message is printed to the console.

Source Code

class Printer
{
	void print(String text)
	{
		System.out.println("String : " + text);
	}
 
	void print(int num, String... messages)
	{
		System.out.print("Integer : " + num + " , Messages : ");
		for (String message : messages)
		{
			System.out.print(message + " ");
		}
		System.out.println();
	}
 
	public static void main(String[] args)
	{
		Printer printer = new Printer();
		printer.print("Hello World");
		printer.print(84, "Java is", "awesome");
	}
}

Output

String : Hello World
Integer : 84 , Messages : Java is awesome

Example Programs