• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Help with Switch

 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
best scout
Posts: 1294
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks lot!!

I got it now

Sneha
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic