Method Overloading with Changing Numbers of Parameters and Data Types in Java


Write a Java program to demonstrate method overloading with changing the number of parameters and data types

This Java program defines a class named StringOperations with several overloaded concat methods. Overloading means having multiple methods with the same name but different parameter lists.

  • The main method creates an instance of the StringOperations class.
  • It then calls the concat methods with different arguments.
  • The Java compiler determines which method to call based on the number and type of arguments passed.
  • For each call to concat, the appropriate version of the method is invoked and the concatenated string is returned.
  • The concatenated strings are then printed to the console.

Source Code

class StringOperations
{
	String concat(String str1, String str2)
	{
		return str1 + str2;
	}
 
	String concat(String str1, String str2, String str3)
	{
		return str1 + str2 + str3;
	}
 
	String concat(int num, String str)
	{
		return num + str;
	}
 
	public static void main(String[] args)
	{
		StringOperations strOps = new StringOperations();
		System.out.println("Concatenation 1 : " + strOps.concat("Hello ", "World"));
		System.out.println("Concatenation 2 : " + strOps.concat("Java", " is", " fun"));
		System.out.println("Concatenation 3 : " + strOps.concat(47, " is the answer"));
	}
}

Output

Concatenation 1 : Hello World
Concatenation 2 : Java is fun
Concatenation 3 : 47 is the answer

Example Programs