0

when i run the below code, it give the output "Arithmetic exception". Since the Arithmetic Exception is checked Exception, so it has higher priority than unchecked exception. But how does it distinguishes between object and Arithmetic exception?

public class Solution {


public static void a(Exception e)
{
    System.out.println("Exception");

}
public static void a(ArithmeticException ae)
{
    System.out.println("ArithmeticException");
}

public static void a(Object o)
{
    System.out.println("Object");
}

public static void main(String[] args)
{
    a(null);
}

}

prabhakar Reddy G
  • 1,039
  • 3
  • 12
  • 23
  • 1
    The answer below is correct. You should also note that an `ArithmeticException` is not a checked exception. – Paul Boddington Oct 05 '15 at 04:28
  • 1
    Possible duplicate of [Method overloading and choosing the most specific type](http://stackoverflow.com/questions/9361639/method-overloading-and-choosing-the-most-specific-type) – Oleg Estekhin Oct 05 '15 at 04:40

2 Answers2

4

When you overload methods, most specific method will be choosen. In your case the order of choosing is

Arithmetic Exception > Exception > Object

As per Language specification most specific method chooses at run time.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

Arithmetic Exception is more specific than Exception which is more specific than Object

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Java language will choose the most specific match in the case of method overloading with arguments which are related to one another through inheritance.

We shall demonstrate this behavior using an example

    public static void main(String[] args) {
        a(new Exception("some exception"));
        a(new ArithmeticException("something went wrong with numbers."));
        a(new String("hello world"));
        a(null);
    }

The output is as expected : enter image description here

deepak marathe
  • 409
  • 3
  • 10