• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Dan Chisholm's question from chapter 5

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can any please give an explanation to the answer of this question:
class Black {
public static void main (String args[]) {
int i = 0;
int j = 0;
label1:
while (i++<5) {
label2:
for (; {
label3:
do {
System.out.print(i + j);
switch (i+j++) {
case 0: continue label3;
case 1: continue label2;
case 2: continue label1;
case 3: break;
case 4: break label3;
case 5: break label2;
case 6: break label1;
default: break label1;
}
} while (++j<5);
}
}
}
}

What is the result of attempting to compile and run the above program?
a. Prints: 12457
b. Prints: 02357
c. Prints: 02356
d. Prints: 1357
e. Prints: 1356
f. Runtime Exception
g. Compiler Error
h. None of the Above
Answer given is a.
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch Sarbani. Please see below the link "What is UBB Code?" to ident properly your code.

1)i=0,j=0
2)after point A i=1
3)C prints 1
4)D evalutes to continue label 2. Independently of that j=1 after D
5)continue label 2 will break E, that is, j is still 1. If B had gotten an increment expression it would have been executed.
6)C prints 2
7)D evalutes to continue label 1. After D j=2
8)continue label 1 will break E again, that is, "++j<5" is not executed. If A had gotten an increment expression it would have been executed before "i++<5".
9)In A 1<5 and i=2 after A
10)C prints 4
11)D evalutes to break label 3. After D j=3
12)break label 3 breaks E and the next B iteration begins
13)C prints 5
14)D evaluates to break label 2. After D j=4
15)break label 2 breaks E and B. The next A iteration begins. If A had gotten an increment expression it would have been executed before "i++<5"
16)in A 2<5 and after A i=3
17)C prints 7
18)D evaluates to default. After D j=5
19)break label 1 jumps out of A ending the program.
Hope it helps.
[ March 23, 2003: Message edited by: Jose Botella ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic