No Preprocessor
Home ] Up ] Program Structure & Environment ] Comments ] Primitive Data Types ] Reference Data Types ] [ No Preprocessor ] Typesafe enums ]

 

 

Java has no Preprocessor like C and C++.

Here's  how Java does things that you often use the preprocessor to do in C/C++:

Defining constants

Instead of:
#define PI 3.14159	// C or C++

in Java, use something like:

public final class Math
{
    ...
    public static final double PI = 3.14159;
    ...
}
Note:
  1. The uppercase convention of C is the same in Java.

  2. Java constants have properly scoped names, unlike #define

  3. Java constants are properly typed, unlike #define

  4. In Java, final is like C or C++ const.

Defining macros

Instead of:
#define min(x, y) (((x) < (y))? (x) : (y))	// C or C++
write it as a function and trust the compiler to do the right thing.

A good Java compiler will inline code where appropriate

Including files

Java does not have any way to include a file.  It has no need, because:
  • Java defines a mapping of fully qualified class names (like java.lang.Math) to a directory and file structure.
  • Java does not distinguish between declaring and defining a variable or procedure, as do C and C++.
  • Java has an import statement, which tells the compiler what packages are being used by this file.  
    • An import statement is not the same as an #include in C/C++)

Conditional Compilation

Java has no equivalent to the C and C++ #ifdef ... #endif directives for conditional compilation.

In theory, Java doesn't need conditional compilation, because it's much more portable at the source code level than is either C or C++.

In practice, it is still used:

class MyClass
{
    private static final boolean DEBUG = false;
    ...
    {
        ...
        if (DEBUG)
        {
            /* debugging code */
        }
        ...
    }
    ...
}
Note that, here, if the value of DEBUG (a static final)is set to false, then the compiler will notice that the debugging code will never be invoked, and simply not include it (optimize it out) in the resulting class file.

 

This page was last modified on 02 October, 2007