Switch case doubt

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

Posts: 74

posted 10 years ago

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

posted 10 years ago

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.