Java Constant Variable – Declaration and Usage of Constants

1 Flares Twitter 0 Facebook 1 Google+ 0 LinkedIn 0 1 Flares ×

C++ has a nice way of declaring constants using the constant keyword. There is no such keyword in java.Then how does java programmers declare constants ?

Java indeed has constant declaration support, but using a different keyword – final. A final variable in java is equivalent to C++ constant. The final keyword is declared before a constant to indicate that its value remains a constant once it is initialized and cannot change. Any attempt to change its value will result in a compile time error.

1) Constant (final)  Variable Declaration

final int a =0;

In java, we always combine static and final together to make it more effective. static indicates that it is a class level variable and is available with out any instances of the class. It just means this variable is available to all instances of the class “as it is”.The static variable gets memory only once in class area at the time of class loading. Hence it makes sense to declare a constant field also as static as it remains the same for all instances.

Better Constant declaration and usage

public static final int MAX_QUANTITY = 512;

We normally, use ALL CAPS to name a variable declared as constant using final and /  static.

Above code will throw compile error, because a final variables value cannot be changed once it is initialized.

2) Final (Constant) method in Java

Java treats the final keyword differently when applied to a variable and a method. When applied to a method, it means the sub classes are forbidden from overriding that method. We use final methods when we want the sub classes to use the method declared in the super class, as it is.

Example of final method

Above code will throw a compiler error, as the subclass is trying to over-ride the final method declared in the super class.

3) Final Class

When final keyword is applied to a class, it means it is not available for sub classing. You simply cannot extend it. This is a nice way of preventing other classes from inheriting from the final class.

  1. final variable – Cannot change its value once initialized
  2. final method – Sub Classes cannot over ride the method
  3. final class – Not available for sub classing. Other classes cannot extend from this

Best Practices

Usually,constants are defined and declared as final static fields in an abstract class. This is one of the best practice followed by many developers. An abstract class is used to denote that there are no method implementations within the class and hence an ideal choice to keep constants.