File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes unreachable code-K&B p343 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 "unreachable code-K&B p343" Watch "unreachable code-K&B p343" New topic

unreachable code-K&B p343

prajal Mehta
Ranch Hand

Joined: Dec 03, 2007
Posts: 66

The following code doesn't compile saying the code is unreachable-

But following code (from K and B , page 343) does compile, even though the line - ' System.out.println("outer");' is never going to print , then why doesn't compiler treats it as unrechable code? :roll:

I am confused.
Please somebody give me tips on how to determine if a given line of code is unreachable and when will the program fail to compile?

I am planning to give my scjp exam on thursday!
[ January 07, 2008: Message edited by: prajal Mehta ]
srinivas sridaragaddi
Ranch Hand

Joined: Jul 24, 2007
Posts: 225
Hi prajal,

Some situations where in unreachable statement error is thrown are statements after continue,break,return,if the condition is set to false etc....

their are some other cases. In your example when control reaches continue control has to be moved to label outer and hence for any value of i,j the
statement System.out.println("Outer"); is not executed hence unreachable statement error is thrown.

consider this

System.out.println("hello");//unreachable statement

in this case also compiler knows that the condition is always false hence the statement inside the loop is never going to execute and hence unreachble statement.

where are the same is not true in this case

System.out.println("hello");//compiles fine

even though the condition is false for the given value, compiler thinks that values of i and j can be changed or chances of condition becoming true exists and hence no error.

Hope this helps
[ January 07, 2008: Message edited by: srinivas sridaragaddi ]

SCJP 5.0<br /> <br />"Skills are started with learning and mastered with improvement. Nothing is hereditary except death" BUDDHA...
Raman Gopalan

Joined: Jan 07, 2008
Posts: 10
I agree with sreenivas..correct me if i am wrong
This is from the specification : Pg 402
"...the values of expressions are not taken into account in the flow analysis"

In this case,
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
continue outer;
} // end of inner loop
System.out.println("outer"); // Never prints --but why

the inner loop's condition expression ( j <5) can be replaced by j <0 and thus, System.out.println("outer") can be made reachable .
Thirumalai Muthu
Ranch Hand

Joined: Oct 07, 2007
Posts: 75
Excellent explanation srinivas and raman

I agree. Here's the link:
subject: unreachable code-K&B p343
It's not a secret anymore!