Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Compiler: Stop complaining about dead code

For testing purposes, I often start typing some code in an already existing project. So, my code I want to test comes before all the other code, like this:

public static void main(String[] args)
{
    char a = '%';
    System.out.println((int)a);
    // To know where '%' is located in the ASCII table.

    // But, of course, I don't want to start the whole project, so:
    return;

    // The real project starts here...
}

But the compiler complains about the return-statement, because of the following "dead code". (While in C++ the compiler obeys the programmer and simply compiles the return statement)

To prevent the compiler complains, I write a stupid if-statement:

if (0 != 1) return;

I hate it. Why can't the compiler do what I ask? Are there some compilation flags or annotations or whatever to solve my problem?

Thanks

like image 507
Martijn Courteaux Avatar asked Mar 08 '11 09:03

Martijn Courteaux


2 Answers

There are no flags to turn of this behaviour. The rules that make dead code a compile time error are part of the JLS (§14.21 Unreachable Statements) and can't be turned off.

There's an explicit loophole in the loop which allows code like this:

if (true) return;

someOtherCode(); // this code will never execute, but the compiler will still allow it

This is done explicitly to allow "commenting-out" or conditional compilation (depending on some static final boolean flag).

In case you're curious: the loophole is based on the fact that a known-constant value of the condition expression of an if statement is not considered when checking reachability of code within or after the if statement. A similar situation occurs with while, where known-constant values are considered, so this code will not compile:

while (true) return;

someOtherCode(); // this will be flagged as an unreachable statement
like image 107
Joachim Sauer Avatar answered Oct 09 '22 01:10

Joachim Sauer


You shouldn't have lots of dead cod ein your project however two ways I get around this for prototyping.

Use /* */ to comment out the code.

    // But, of course, I don't want to start the whole project, so:
    /*
    // The real project starts here...


    */
}

or create a second method.

    // But, of course, I don't want to start the whole project, so:
    // realProject();
}

public static void realProject()
    // The real project starts here...
}
like image 38
Peter Lawrey Avatar answered Oct 09 '22 01:10

Peter Lawrey