What – constants in Java
While Java does not have a built-in Constant type, functionally constants are supported through the use of two modifiers: final and static, like this:
public static final int NUM_CARDS_IN_DECK=52;
First, we define the variable as public, this is not necessary for using the constant within the same class, but is needed in order to access the same constant from multiple classes. I will go into this distinction in more detail later.
Secondly we mark it as static. This provides two related features. The variable can be referenced without instantiating a copy of it’s enclosing object. The variable will only exist ONCE in memory. This is very efficient. Also, during compilation the access will be in-lined into the class and therefore much faster.
Thirdly we mark it as final. This prevents the value from being changed or overridden, ensuring that that the value is consistent throughout your entire application, and letting the compiler know it does not have to worry about the value changing.
From there it looks like a normal variable except for the name. The convention is to name constants in all capitals with underscore characters separating logical words.
Continue reading