This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes j++ IN switch() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "j++ IN switch()" Watch "j++ IN switch()" New topic
Author

j++ IN switch()

Hades Pan
Ranch Hand

Joined: Nov 25, 2001
Posts: 106
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

Joined: Nov 29, 2001
Posts: 162
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

Joined: Jul 22, 2000
Posts: 9044
    
  10

I agree with Jim.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Bunty Naidu
Greenhorn

Joined: Jan 10, 2001
Posts: 6
Ya Jim, you're right. The answer is 5)2.
Mr Iftikhar
Ranch Hand

Joined: Oct 12, 2001
Posts: 39
Yes the code is fine and will print 2 on the console.

java language
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: j++ IN switch()
 
Similar Threads
switch
why and how output is 8
java.ditmas.net mock
Question about local variables in switch
switch construct