Evaluation of conditional expressions in Java

Asked

Viewed 98 times

2

I’ve been observing that conditional expressions in Java that are formed only by literals or constants (or operations between them) are evaluated in different ways. Therefore, 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 other section does not compile. The compiler complains of "Unreachable code" only in the part of while, the part within the 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" inside blocks if as in the above example are also treated as compile-time errors. Does anyone know of any flag I can pass to the compiler for this to happen? (if this flag exists) Or a similar mechanism?

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 chooses to omit it and not generate an "unreachable code" error. This differentiated treatment in relation to the WHILE loop is useful, mainly so that programmers can 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: http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.21

2

I do not believe that the compiler javac have any option for this.

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

Performing static analysis means scanning the source code or bytecode for common errors, incorrect syntax, and bug risks.

If the project uses Maven, Gradle or some other tool to do the build, can integrate the analysis into the process so that it runs automatically and generates errors if any rule is broken.

Ides such as Eclipse and Intellij have plugins capable of integrating analysis with these tools and, by themselves, are also able to perform some analysis. In general, these Ides have settings to increase the problem level of a warning (Warning) for an error, forcing the developer to fix the problem.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.