File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes dead code unreachable code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "dead code unreachable code" Watch "dead code unreachable code" New topic

dead code unreachable code

veena bijur
Ranch Hand

Joined: May 16, 2011
Posts: 67

Why System.out.println("hello"); not considered as unreachable code rather considered as dead code?

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

If my memory serves me correctly, you had asked the exact same question before.

~ Mansukh
Lalit Mehra
Ranch Hand

Joined: Jun 08, 2010
Posts: 384

Hello Veena,

It is Because this System.out.println() is compiled though never used.

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11951

also, remember that the compiler is not as smart as humans. It doesn't/can't check everything that you it doesn't realize that the break will always be executed

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
As usual, the compiler is obeying the JLS, which specifically requires that an if statement be treated this way. Here's the explanation:
As an example, the following statement results in a compile-time error:

because the statement x=3; is not reachable; but the superficially similar case:

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

and then write code such as:

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

In reality, no one uses DEBUG like this anymore; they use proper logging frameworks (which will work better once we get lamdas). But back in the mid-nineties, such code was not too uncommon among the C/C++ programmers that Java was targeting for its audience.
I agree. Here's the link:
subject: dead code unreachable code
It's not a secret anymore!