my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes kathy sierra self test question(Exception)? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "kathy sierra self test question(Exception)?" Watch "kathy sierra self test question(Exception)?" New topic

kathy sierra self test question(Exception)?

Hennry Smith

Joined: Jan 21, 2011
Posts: 26

And given that line 7 will assign the value 0, 1, or 2 to sw, which are true? (Choose all that apply.)
A. Compilation fails
B. A ClassCastException might be thrown
C. A StackOverflowError might be thrown
D. A NullPointerException might be thrown
E. An IllegalStateException might be thrown
F. The program might hang without ever completing
G. The program will always complete without exception

D and F are correct. Because i was not initialized, case 1 will throw an NPE. Case 0 will
initiate an endless loop, not a stack overflow. Case 2's downcast will not cause an exception.

Please explain this question ...which exception will b thrown and why....???
Meena Ajay
Ranch Hand

Joined: May 28, 2008
Posts: 38

Hi Hennry,

As given in the answer,D and F are correct.

At Line 5., the Static Integer i is declared, but not initialized anywhere in the code.Default value would be null.

Case 1:
So, if the output of the expression at line 7. assigns the value for sw as 1, then case 1: would be executed where x is having null value and when the int value of x is tried to be automatically unboxed, it will throw a Null pointer exception.

For this case, D will be the answer.

Case 0:
If the sw value is assigned a value of 0 at line 7., then case 0: would be executed where x is set to 10 and the condition checked in the for loop will always be true.Since x is only incremented in this block, the condition x> 5 will always be true.So, this will be an endless loop.

For this case, F will be the answer.

Hope this helps.

Cheers, Meena
Hennry Smith

Joined: Jan 21, 2011
Posts: 26
thanks i got it....
Don't get me started about those stupid light bulbs.
subject: kathy sierra self test question(Exception)?
It's not a secret anymore!