• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Which code compiles, but throws an exception...confused about the answer

 
Larry Olson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

This code/question is from the SAI sample e-practice exam:



The question is:

Which code, inserted at line 11, will compile, but cause an exception to be thrown at runtime?

A. a2.m2();
B. ((Beta)a2).m2();
C. ((Alpha)a2).m2();
D. ((Gamma)a2).m2();

The answer and explanation are:
Option D is correct. Options A and C will NOT compile, option B will compile and run. Option D throws an exception because type Alpha has no m2 method.

But when I try option D, the code compiles and Runs fine. No exception is being thrown. The above answer and explanation doesn't make sense to me. In fact none of the answer choices seem to be correct. I am confused. What is the right answer and why?

Thanks.
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is right. It does throw an exception on my system. Can you create a new GreekTest.java file in an empty folder with the code you posted, recompile it and then run it to see the output. Sometimes existing .class files can result in unpredictable behavior...
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yea... It gives a RuntimeException to me also!~

Short circuit operator(||) check its first boolean expression, if that is false only, it will check the second boolean expression.... Here you can't cast a Beta object to a Gamma object.. so, ClassCastException will be thrown.....
 
Pragyan Nayak
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, option D generates an exception as shown below.

Exception in thread "main" java.lang.ClassCastException: Beta cannot be cast to Gamma
at GreekTest.main(GreekTest.java:11)
 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I understand what is going on

Below is the code and corresponding explanations



a2.m2(); : Reference variable is of type Alpha, so the compiler sees that Alpha doesn't have m2 method
((Beta)a2).m2(); : Will run and compile because you are casting an Alpha reference variable as Beta. It is as if the reference variable is Beta, which has method m2()
((Alpha)a2).m2(); : You are casting reference variable Alpha as Alpha so it's just as if you would have written a2.m2();
((Gamma)a2).m2(); : Beta cannot be cast to Gamma. This is a downward cast and there is no guarentee that whatever Gamma can do, Beta can do



Please feel free to clarify these points.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic