Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Testing
Expertise: Beginner
Jun 6, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Preprocessor Support

Is there something similar to the C/C++ compiler directive #ifdef, #define, and #endif in Java? I would like to compile debugging code conditionally.

This is one of the first questions that crossed my mind when I first started programming in Java. The disappointing answer is no. Not everyone agrees on the need for Java to include flexible conditional compilation support or some of the other beneficial features provided by a preprocessor.

Nonetheless, there are several rather compelling reasons for using a preprocessor beyond conditionally compiling debugging code. The most compelling reason that developers are facing on an increasing basis is the need to maintain different versions of classes from the same source file. A prime example of this today is when you need to support a class library for both Java 2 Standard Edition and Java 2 Micro Edition. When all you have to do is remove import java.io.* and make a class not implement java.io.Serializable to make it work for J2ME, conditional compilation is just the right thing. Even though there are alternative ways of approaching the problem, they typically result in code bloat.

For the case of maintaining debugging code, a widely suggested approach is to declare a static final Boolean constant, initializing it to True when you want to turn debugging on and to False when you want it off. Then place debugging code inside an If statement that tests the value of the constant. This allows the compiler to optimize out all debugging code when the constant's value is equal to False. This approach is inadequate for solving the general problem of conditional compilation, but it will allow you to conditionally include debugging code.

You may want to search the Web for one of several preprocessor implementations for Java, but keep in mind that none of them is standard.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date