Java Preprocessor
Asked Answered
F

2

45

If I have a boolean field like:

private static final boolean DEBUG = false;

and within my code I have statements like:

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

does the Java preprocessor just get rid of the if statement and the unreachable code?

Fertilization answered 27/8, 2009 at 23:26 Comment(4)
"The Java language has no preprocessor," (java.sun.com/developer/JDCTechTips/2003/tt0408.html) Are you talking about the Java Compiler?Operand
Thanks for the article, I didn't know Java doesn't have a preprocessor. So I am just talking about the compiler.Fertilization
It's true that Java doesn't have a preprocessor with the same capabilities as that of C/C++. However it does have annotation processors which offer compile-time processing. See Oracle's Annotations TutorialJospeh
The link above is broken ... it's now docs.oracle.com/javase/tutorial/java/annotationsSibylle
G
117

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 a listing of the produced instructions via the javap command:

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, no System.out.println! :)

Gratulant answered 27/8, 2009 at 23:34 Comment(1)
also, I checked when you have a statement that is something like if(DEBUG && condition_that_may_be_true) ..., and if DEBUG is always false it cuts it out.Fertilization
R
13

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

Ruisdael answered 27/8, 2009 at 23:31 Comment(3)
Can you give the Java Language Specification page that states this?Yellowgreen
@Ralph: See 14.21 Unreachable Statements for the discussion in the JLS. The bit about the if statement is right near the end of that section.Ruisdael
Page now here for jse7: docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21 and here for jse5: docs.oracle.com/javase/specs/jls/se5.0/html/…Cooley

© 2022 - 2024 — McMap. All rights reserved.