aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Switch case doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Switch case doubt" Watch "Switch case doubt" New topic
Author

Switch case doubt

Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
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:



SCJP 5.0 77%
sentil kumar
Ranch Hand

Joined: Oct 23, 2006
Posts: 74
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

Joined: Nov 07, 2006
Posts: 65
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Switch case doubt
 
Similar Threads
About Static blocks
Downward casting
Constructor
switch doubt..
Strange Output