Evaluation of conditional expressions in Java

2

I have been observing that conditional expressions in Java that are formed only by literals or constants (or operations between them) are evaluated in different ways. So, the code below compiles normally:

public class Main {

    public static void main(String[] args) {
        if (true) {
            System.out.println("teste");
        }
        while (true) {
            System.out.println("teste");
        }

    }
}

However, this section does not compile. The compiler complains of "Unreachable code" only in the while part, the part within if is also "unreachable".

public class Main {

    public static void main(String[] args) {
        if (false) {
            System.out.println("teste");
        }
        while (false) {
            System.out.println("teste");
        }

    }
}

I wonder if it is possible to make "unreachable codes" within if blocks as in the example above also be treated as compile-time errors. Does anyone know of any flag I can pass to the compiler for this to happen? (if that flag exists) Or a similar mechanism?

    
asked by anonymous 05.12.2016 / 22:32

2 answers

3

There is an optimization done by the compiler that actually identifies that the code inside the IF will not be executed, but only chooses to omit it and does not generate an "unreachable code" error. This differential treatment in relation to the WHILE loop is useful, mainly for programmers to define DEBUG and RUNTIME flags:

static final boolean DEBUG = false;
if (DEBUG) {
...
...
...
}

The above condition would be impossible if the compiler decided to throw unreachable code errors, instead of omitting the code inside the IF when it is not DEBUG

Reference: link

    
05.12.2016 / 22:52
2

I do not think the compiler javac has any option for this .

However, in this case, it is advisable to use at least one (may be more) of the static code analysis tools, such as: Checkstyle, PMD and Findbugs .

Static scanning means scanning the source code or bytecode for common errors, incorrect syntax, and risk of bugs.

If the project uses Maven , Gradle, or some other tool for doing build , can integrate analysis into the process so that it runs automatically and generates errors if any rules are broken. p>

IDEs such as Eclipse and IntelliJ have plugins capable of integrating analysis with these tools, and by themselves are also capable of performing some analysis. In general, these IDEs have settings to raise the level of a warning problem to an error, forcing the developer to correct the problem.

However, while an IDE works well for individual development, teams often need a standard process, possibly with continuous integration , so the recommended solution is to use a tool such as Maven or Gradle together with the other analysis tools mentioned above.

    
06.12.2016 / 04:32