#define in Java

Meir picture Meir · Dec 18, 2009 · Viewed 187.3k times · Source

I'm beginning to program in Java and I'm wondering if the equivalent to the C++ #define exists.

A quick search of google says that it doesn't, but could anyone tell me if something similar exists in Java? I'm trying to make my code more readable.

Instead of myArray[0] I want to be able to write myArray[PROTEINS] for example.

Answer

Andrzej Doyle picture Andrzej Doyle · Dec 18, 2009

No, because there's no precompiler. However, in your case you could achieve the same thing as follows:

class MyClass
{
    private static final int PROTEINS = 0;

    ...

    MyArray[] foo = new MyArray[PROTEINS];

}

The compiler will notice that PROTEINS can never, ever change and so will inline it, which is more or less what you want.

Note that the access modifier on the constant is unimportant here, so it could be public or protected instead of private, if you wanted to reuse the same constant across multiple classes.