Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch case doubt

 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code:

This gives an error as follows:
test.java:16: unreachable statement
System.out.println("Outside Block 1 ");


But now if put the break in a if statement which is always true. I dont get any error. Why is this difference:

 
sentil kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here the compiler assumes that if condition fails
System.out.println("Outside Block 1 "); will be executed.

if there is no condition for before break,
System.out.println("Outside Block 1 "); will never be executed.
 
Abdul Rehman
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Satish Kota:
But now if put the break in a if statement which is always true. I dont get any error. Why is this difference?

This is a rule laid down by the Java Language Specification. For example, if you write:-

The program will compile smoothly.
However, if you write:

The compiler will generate an error, complaining "unreachable code".

This is a special exception of the if statement. The rationale for this as described by the JLS is that this will allow conditional compilation via constant variables. As an example, consider the following code:-

In the above code, you may add a lot of "debug" code to your program, sandwiched between an if(DEBUG) statement. Later, when you don't need the code, instead of deleting, you can simply change the value of DEBUG from true to false. The special rule provided for the if(...) statement by the JLS, thus allows us to do such things without getting a million "unreachable code" errors.

Best regards,
Abdul Rehman.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic