Java preprocessor

If I have a boolean type field:

private static final boolean DEBUG = false;

and inside my code I have statements like:

if(DEBUG) System.err.println("err1");

Is the Java preprocessor just getting rid of the if statement and unreachable code?

+41
java optimization preprocessor
Aug 27 '09 at 23:26
source share
2 answers

Most compilers will eliminate the statement. For example:

 public class Test { private static final boolean DEBUG = false; public static void main(String... args) { if (DEBUG) { System.out.println("Here I am"); } } } 

After compiling this class, I then print the list of generated instructions using the javap :

  javap -c Test
     Compiled from "Test.java"
     public class Test extends java.lang.Object {
     public Test ();
       Code:
        0: aload_0
        1: invokespecial # 1;  // Method java / lang / Object. "" :() V
        4: return

     public static void main (java.lang.String []);
       Code:
        0: return

     }

As you can see, there is no System.out.println ! :)

+109
Aug 27 '09 at 23:34
source share

Yes, the Java compiler will eliminate the compiled code in if blocks that are controlled by constants. This is an acceptable way to conditionally compile "debug" code that you do not want to include in a production assembly.

+12
Aug 27 '09 at 23:31
source share



All Articles