Method Overloading with Multiple Methods Having the Same Name but Different Parameter Counts in Java


Create a Java program to demonstrate method overloading with multiple methods having the same name but different parameter counts

This Java program defines a class named Example with multiple overloaded print methods, each accepting different types of parameters. Let's break down the code:

  • The main method creates an instance of the Example 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 Example
{
	void print()
	{
		System.out.println("No Parameter");
	}
 
	void print(int num)
	{
		System.out.println("Integer : " + num);
	}
 
	void print(String message)
	{
		System.out.println("String : " + message);
	}
 
	public static void main(String[] args)
	{
		Example example = new Example();
		example.print();
		example.print(67);
		example.print("Hello World");
	}
}

Output

No Parameter
Integer : 67
String : Hello World

Example Programs