• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dan exam doubt 11

 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, if it gives a compile-time error, it isn't going to run is it?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic