File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes switch statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "switch statement" Watch "switch statement" New topic
Author

switch statement

Chris Davies
Ranch Hand

Joined: Feb 26, 2003
Posts: 110
hi

i came across the following switch statement but couldn't work it out

int i= 1

switch (i)
case 1: i++
case 2: i++
case 3: i++
case 4: i++

default: i++

does it increment after it matches case 1 ? does it contiunue incrementing after each case as there is not break statement ?

cheers

chris


One day all greenhorns will run free ...
Lionel Badiou
Ranch Hand

Joined: Jan 06, 2005
Posts: 140
Hello Chris,

1- Obviously, this code doesn't even compile
2- Sun's docs say: "The break statements are necessary because without them, the case statements fall through. That is, without an explicit break, control will flow sequentially through subsequent case statements."

Hope that helps,


Lionel Badiou
CodeFutures Software
Learning Nuky
Greenhorn

Joined: Jan 19, 2005
Posts: 1
Here is a small program that shows the syntax of switch. I hope this helps to understand how it works. Please compile and substitute different values for i at the beginning in order to see how the switch operates.



Nuky.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Maybe I can guess your next question: Why doesn't Java just do an implicit break after each case? Why make me type it for each case? The answer is that this allows some nice possibilities:
Nikhilesh Fonseca
Ranch Hand

Joined: Aug 23, 2004
Posts: 57
Your Code will chk for the first value that matches the case ...It will then execute everything after that till it come to a break or till it exits the block
So if u try out a system.out.println() after each case:i++
u will c what i mean .As such i is incremented aneeway.
If your first case isn't 1 then it will search for the value which matches i
and then execute all other cases therafter including your default case.
If there is break aneewhere in between it will as is obvious break out of the switch statement.
Cheers
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: switch statement
 
Similar Threads
Assertion ?
Can't understand this tricky for loop question
Khalid's Mock exam engine question
Questions about switch
Assertion Question