Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Help with Switch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help with Switch " Watch "Help with Switch " New topic
Author

Help with Switch

sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
Hear is my question for simple switch statement
class MissingBreak
{
public static void main(String[] args)
{
int i =0;
switch (i)
{
case 0:
System.out.println("i is 0");
case 1:
System.out.println("i is 1");
}
}
}
I declared the i value as 0 then only the case with 0 should execute then why case 1 is executing?
I read in the book that break is optional?
Please tell me how the flow is going?

Thanks in advance
Suma
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1280

Hi sumaraghavi,

indeed the break statement for each case is optional but without a break; execution just falls through all other cases. So if you want only the statements for case '0' to be executed you'll have to insert a break at the end of case '0'

Marco
Schevus Osborne
Greenhorn

Joined: Jan 21, 2008
Posts: 7
Break is optional, but if a case statement does not have a break the flow will continue on to the next case statement.

- Schev
sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
Thanks lot!!

I got it now

Sneha
 
 
subject: Help with Switch
 
Similar Threads
Problem in switch statement
Switch statement
why is the code complining
SCJP question on loop
Can't understand this tricky for loop question