| Author |
dan exam doubt 11
|
amit taneja
Ranch Hand
Joined: Mar 14, 2003
Posts: 806
|
|
hii in one question Question 20 class C { String m1(int i) { switch (i) { case 0: return "A"; case 1: return "B"; case 2: return "C"; default: assert false; } } public static void main(String[] args) { C c = new C(); for (int i = 0; i < 4; i++) { System.out.print(c.m1(i)); }}} Which statements are true? a. With assertions enabled it prints ABC followed by an AssertionError message. b. With assertions disabled it prints ABC followed by an AssertionError message. c. Assertions should not be used within the default case of a switch statement. d. In this code example a throw statement must be used in place of the assert statement. e. Compile-time error the answer are "d and e" but why not "a" ? pls explain...
|
Thanks and Regards,<br />Amit Taneja
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
|
Well, if it gives a compile-time error, it isn't going to run is it?
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
When checking for semantic errors, the compiler considers worst cases. The JLS calls this conservative flow analysis. In this example, the worst case is when assertions are disabled and flow reaches the end of method m1() without a return statement. You won't get a chance to enable asertions at execution time because the code won't compile. One way to fix the problem is to use "throw new AssertionError();" instead of "assert false:". Then the compiler knows that you will never get past the case statement regardless of whether assertions are enabled at execution timen - you must either return or throw an exception. I have trouble with the phrase "a throw statement must be used in place of the assert statement", since there are other good ways to fix this code.
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
 |
|
|
subject: dan exam doubt 11
|
|
|