Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define in Java

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.

like image 301
Meir Avatar asked Dec 18 '09 08:12

Meir


1 Answers

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.

like image 195
Andrzej Doyle Avatar answered Oct 13 '22 05:10

Andrzej Doyle