Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Preprocessor

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?

like image 509
twolfe18 Avatar asked Aug 27 '09 23:08

twolfe18


People also ask

What is preprocessor in Java?

A preprocessor is a program that works on the source before the compilation. As the name implies, the preprocessor prepares the source for compilation. The notion of the preprocessor has been there from the earliest times of programming languages.

Does Java require a preprocessor?

Source code written in Java is simple. There is no preprocessor, no #define and related capabilities, no typedef , and absent those features, no longer any need for header files. Instead of header files, Java language source files provide the declarations of other classes and their methods.

How do you create a preprocessor in Java?

Java doesn't have a preprocessor - so the simple answer is that you can't. This sort of thing is normally handled in Java using Dependency Injection - which is both more powerful and more flexible.

What is preprocessor used for?

In computer science, a preprocessor (or precompiler) is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers.


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

like image 122
Adam Paynter Avatar answered Sep 18 '22 19:09

Adam Paynter


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.

like image 21
Greg Hewgill Avatar answered Sep 22 '22 19:09

Greg Hewgill