• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

switch

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 int i = 1,j = -1;
2 switch (i) {
3 case 0, 1:j = 1;
4 case 2: j = 2;
5 default; j = 0;
6 }
7 System.out.println("j="+j); What is the result?

A. j = -1
B. j = 0
C. j = 1
D. j = 2
E. Compilation fails.
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
line 3,
case 0,1???


ans: Compilation fails
 
xie li
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why?
 
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Xie,

Answer is "Compilation fails!". Why? Note that java compiler does not understand everything you write.

1 int i = 1,j = -1;
2 switch (i) {
3 case 0, 1:j = 1;
4 case 2: j = 2;
5 default; j = 0;
6 }

Look at line 3. It is syntax error.
Look at line 5. It is syntax error as well in default; (instead of ;,

Correct Version of code is as follow.


1 int i = 1,j = -1;
2 switch (i) {
3 case 0: case 1:j = 1;
4 case 2: j = 2;
5 default: j = 0;
6 }
 
Always! Wait. Never. Shut up. Look at this tiny ad.
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic