Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Conditional directives are used to include or exclude blocks of code from a source file, based on the result of an expression, or the value of a single identifier. Conditional directives are useful in many aspects of development, among them:
They can be used to selectively include or exclude vital diagnostic, or debug code. Once an application containing conditional directive-based code is ready for release, the code can be easily eliminated from the project.
They can be used to experiment with several possible code optimizations. For example, if various implementations of an algorithm need to be examined for efficiency, setting the appropriate conditional identifier can instantly switch the code execution path to a different algorithm.
The following example demonstrates the use of conditional directives:
# define PRINTHELLO // PRINTHELLO has the value 'true'
public class sample {
public static void main(String args[])
{
#if PRINTHELLO
System.out.println("Hello!");
#else
System.out.println("Goodbye.");
#endif
}
}
In the example shown above, the string "Hello!" will be displayed. Removing the #define directive will display the string "Goodbye."
Like standard conditional constructs in Java, several of the conditional compilation directives also make use of expressions that govern their flow. For example, the #if compiler directive, like it’s Java language equivalent — the if statement, makes use of Java identifiers and operators to form expressions. Thus, most of the rules that govern the syntax of creating syntactically correct statements in the Java language also apply to the creation of expressions for conditional directives. One notable exception where the language syntax rules do not apply is in the use of multi-line comment blocks.
Conditional directives must be alone on a line, except for single-line comments. Multi-line comments may not begin or end on the same line as a conditional directive.
Used wisely, conditional directives can save you considerable time and effort in debugging code.