Conditional Directives

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:

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.