Only 48 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



  • Post Reply Bookmark Topic Watch Topic
  • New Topic

j++ IN switch()  RSS feed

 
Hades Pan
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Foo{
public static void main(String args[]){
int x=4,j=0;
switch(x){
case 1:j++;
case 2:j++;
case 3:j++;
case 4:j++;
case 5:j++;
break;
default:j++;
}
System.out.println(j);
}
}
1. 1
2. Compiler error
3. 6
4. 3
5. 2
Ans is Compiler error but why?
 
Jim Hall
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you try to compile it? I see nothing wrong with the code and it compiles fine on my machine. The answer is wrong.
 
Marilyn de Queiroz
Sheriff
Posts: 9079
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I agree with Jim.
 
Bunty Naidu
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya Jim, you're right. The answer is 5)2.
 
Mr Iftikhar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes the code is fine and will print 2 on the console.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!