• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

j++ IN switch()

 
Hades Pan
Ranch Hand
Posts: 106
  • 0
  • 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
  • 0
  • 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: 9059
12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I agree with Jim.
 
Bunty Naidu
Greenhorn
Posts: 6
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes the code is fine and will print 2 on the console.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic