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?

4
  • 2
    "The Java language has no preprocessor," (java.sun.com/developer/JDCTechTips/2003/tt0408.html) Are you talking about the Java Compiler? Commented Aug 27, 2009 at 23:55
  • Thanks for the article, I didn't know Java doesn't have a preprocessor. So I am just talking about the compiler. Commented Aug 28, 2009 at 19:12
  • 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 Tutorial Commented Feb 9, 2013 at 12:24
  • The link above is broken ... it's now docs.oracle.com/javase/tutorial/java/annotations Commented Dec 22, 2016 at 0:50

2 Answers 2

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! :)

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

3 Comments

Can you give the Java Language Specification page that states this?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.