Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why cannot we have a switch case block after a break keyword as part of nested switch case  RSS feed

 
krishnadhar Mellacheruvu
Ranch Hand
Posts: 118
Android Java Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi



now if i give the internal switch after break keyword it gives an error i.e. Code cannot be reached.


What could be the reason for this.

Thanks
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume you are asking about the commented-out break statement in line 19?

Why would you want to insert a break statement there; what would you expect it to do?

A break statement makes the execution jump out of the switch (or a loop), code after the break will never be executed, which is exactly what the error message "unreachable code" means.
 
Ganesh Patekar
Bartender
Posts: 696
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
krishnadhar Mellacheruvu wrote:now if i give the internal switch after break keyword it gives an error i.e. Code cannot be reached.

  • The switch statement transfers control to one of several statements depending on the value of an expression. Here it transfers control to case 1: because of i = 1; which has
  • It executes it then as soon as it reaches unlabeled break statement.
  • JLS 8 14.15. The break Statement wrote:A break statement transfers control out of an enclosing statement.
    A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement of the immediately enclosing method or initializer; this statement, which is called the break target, then immediately completes normally.
  • It transfers it's control out of this switch i.e. in main method so the code beneath the break is unreachable.
  • We can say that nested switch(j) is niether in the scope of case label 1 nor any other.
  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!