Search code examples
javastaticconstantsfinal

Why do we declare constants, and is it necessary to make them static?


I know that constants are those variables whose values cannot be changed, but if no part of the program changes their value, are they still required to be declared final? And it also seems that they must be static. Why is that?


Solution

  • You are actually asking several questions at once which I am trying to answer.

    Why use constants at all?

    Constants are used to avoid magic numbers/strings in your code. If you have a string that appears in several occasions of your code, once you have to change that string you only need to change the constant definition and not every occurrence of the string in your code. Also if a constant is only used once it is often a good thing because of its better visibility.

    The final keyword.

    Its purpose (at least in this context) is twofold. One is to make it impossible to a programmer to change the value. You might have forgotten that it is a constant. The other is to tell the compiler that the value cannot change at runtime. This can be used to create optimized bytecode (e.g. the constant could be removed and every occurrence replaced by its value by the compiler).

    The static keyword.

    In Java everything is a Class. And every Class can have several instances (objects). If you dont mark your constant as static then every object has "its own constant". Since you dont want that it makes sense to mark it as static. Static fields (or methods) do exist only once per class (as opposed to once per object of the class).