Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with Switch

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Schevus Osborne
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks lot!!

I got it now

Sneha
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic