Hi Vinod Pothuru,
First of all, a warm welcome to CodeRanch!
Vinod Pothuru wrote:When the ArrayList type is Exception and object being added is Exception on line 4, why doesn't it get compiled?
Because the compiler does not know about the ArrayList object at the right hand side. Remember the compiler does not execute any code! So the compiler only knows about the type of the reference variable
exceptions (which is
List<? super IOException>). And the compiler is a real smart cookie and he knows, this type declaration allows the following ArrayList objects
Because the compiler only knows about the type of the reference variable, the compiler will
only allow adding elements which can be added to all these lists. If an element can't be added to one of these lists, it will result in a compiler error when you try to add it to
exceptions. So ilet's see what happens if we try to add a new
Exception instance (as in
line4) to any of these lists
line1 results in a compiler error and that's why adding a new
Exception instance (as in
line4) to
exceptions is not allowed and will result in a compiler error. Let's do the same thing with an
IOException (as in
line5)
All these lines compile successfully and that's why you can add a new
IOException instance (as in
line5) to
exceptions without getting a compiler error. And of course the same applies to
FileNotFoundException.
Hope it helps!
Kind regards,
Roel