Method Overloading with Method Ambiguity and Resolution Using Casting in Java


Create a Java program to demonstrate method overloading with method ambiguity and resolution using casting

In the provided Java code, there's a potential ambiguity issue because of the way the arguments are passed to the print method. When you pass a floating-point number, like 38.12, Java can interpret it either as a double or as an int.

  • The main method creates an instance of the AmbiguityExample class.
  • It then calls the print methods with different arguments.
  • In the first call, obj.print((int) 42.9), a double value 42.9 is explicitly cast to an int, resulting in 42.
  • In the second call, obj.print(38.12), the argument is a double value 38.12.
  • The Java compiler determines which overloaded method to call based on the type of the arguments passed.
  • For the first call, the print(int num) method is invoked, as 42 is an integer.
  • For the second call, the print(double num) method is invoked, as 38.12 is a double.

Source Code

class AmbiguityExample
{
	void print(int num)
	{
		System.out.println("Integer : " + num);
	}
 
	void print(double num)
	{
		System.out.println("Double : " + num);
	}
 
	public static void main(String[] args)
	{
		AmbiguityExample obj = new AmbiguityExample();
		obj.print((int) 42.9);
		obj.print(38.12);
	}
}

Output

Integer : 42
Double : 38.12

Example Programs