jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes dan exam doubt 11 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 "dan exam doubt 11" Watch "dan exam doubt 11" New topic

dan exam doubt 11

amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 812

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";
assert false;
public static void main(String[] args) {
C c = new C();
for (int i = 0; i < 4; 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, 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
I agree. Here's the link: http://aspose.com/file-tools
subject: dan exam doubt 11
jQuery in Action, 3rd edition