Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java If(false) Compile

Tags:

java

tomcat

I am developing a dynamic web project using Tomcat. It is useful to have a global flag that is the only thing I have to change between my development and deployment servers. The biggest use of the flag is with print statements.

public class Debug {
    public final static boolean DEVEL = true;        
    public static void print(String message){
        if(DEVEL){
            System.out.println(message);
        }
    }
}

My question is, will java compile out the print statements. i.e. if the devel tag is false, the messages will obviously not print but will they be included in the class files (devel is final). This is a question of efficiency. I've heard that the java compiler is very smart but will it pick up on this.

like image 275
Orlan Avatar asked Jun 04 '11 23:06

Orlan


People also ask

Does Java have conditional compilation?

So Java does have its own conditional compilation mechanism. What if we want to use debugging code similar to this, but have the condition applied at runtime? We can use System. properties (Section 2.3) to fetch a variable.

What does if false mean Java?

if (false) means peace of code which is never executed. If some of your code is unused you should remove it.

Does Java have Ifdef?

Java does not include any kind of preprocessor like the C cpp preprocessor. It may seem hard to imagine programming without #define, #include, and #ifdef, but in fact, Java really does not require these constructs.


3 Answers

use the 'final' attribute (as you did), and it will compile out the code:

public static final boolean DEVEL = false;

You can check by grepping the resultant class file for a string that would appear only if the code were compiled.

like image 81
jcomeau_ictx Avatar answered Sep 20 '22 14:09

jcomeau_ictx


Take a look into this article:

http://www.javaworld.com/javaworld/jw-03-2000/jw-03-javaperf_4.html

The code you presented is called a "dead code" so it will not be included in the compiled class file if you set DEVEL to false it will not be included in the bytecode.

Also, check the command

javap -c

to see the resulting bytecode of your class.

like image 6
chemical Avatar answered Sep 20 '22 14:09

chemical


If you want to have the compiler not compile it out, use this:

    public final static boolean DEVEL = Math.random() > -1;

The compiler won't know that this is always true. (of course use < -1 for false)

I find this trick handy when you want to remove code temporarily without having the compiler complain abut dead code, eg:

void myMethod() {
    // temporarily exit early
    if (Math.random() > -1) return;
    // usual code
}
like image 1
Bohemian Avatar answered Sep 20 '22 14:09

Bohemian