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.
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.
if (false) means peace of code which is never executed. If some of your code is unused you should remove it.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With