my dog learned polymorphism
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Switch case doubt" Watch "Switch case doubt" New topic

Switch case doubt

Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
Consider the following code:

This gives an error as follows: 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:
subject: Switch case doubt
It's not a secret anymore!