In the above code, I thought as x is always zero and not updated and because of the continue statement, System.out.println(j) will never be executed .so, I answered this question as "the code doesn't compile" but I was wrong.
May be is this because compiler thinks after line A there are chances of updating "x"?
what are the tips/tricks is to easily identify unreachable code?
P.S: Only zero is passed as an argument to the method in above code.
All I can see is that the value of x never changes. I can't tell that it's always zero because, for example, the value of x passed to the method might be 42. But we don't see any code like that.
However... even if you and I could see that the value of x is zero and never changes, the compiler can't see that. The compiler isn't a programmer and it doesn't attempt to analyze code except in the most trivial ways, and those ways are specified in the JLS. For the exam you should certainly familiarize yourself with the ways that the compiler deems code unreachable, though. There's only a few of them.
You’re right. System.out.println(j) will never be executed; however, the compiler allows unreachable code caused by an if block in order to allow programmers to define "flag variables" for testing and debugging.
The JLS explains why the compiler allows this.
JLS However, in order to allow the if statement to be used conveniently for "conditional compilation" purposes, the actual rules differ.
JLS The rationale for this differing treatment is to allow programmers to define "flag variables" such as:
Vidya Shivram wrote:what are the tips/tricks is to easily identify unreachable code?
Luckily for you, the "unreachable code" topic is one of the more popular ones in this forum. So using the search function you'll find plenty of topics about "unreachable code". Here is a list which could probably be added to my certification book