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
posted
0
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.
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
i=2; j=3; while(i>j) { 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
Greenhorn
Joined: Jan 07, 2008
Posts: 10
posted
0
Hi, 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, outer: for (int i=0; i<5; i++) { for (int j=0; j<5; j++) { System.out.println("Hello"); 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 .