• Main Menu
  • How to Declare a Constant in Java


    Java does not directly support constants. However, a static final variable is effectively a constant.

    The static modifier causes the variable to be available without loading an instance of the class where it is defined. The final modifier causes the variable to be unchangeable.

    Ex: public static final int FOUNDING_YEAR = 2001;

    Naming Standards for Java Constants

    Although these aren’t syntactical rules, they are widely used as accepted conventions.

    1. Java constants are normally declared in ALL CAPS.
    2. Underscores normally separate Words in Java constants.

    Sample Java Constant Declaration

    public class MAX_UNITS {
     public static final int MAX_UNITS = 25;

    Videos Related to Java Constant Declaration

    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    2 comments
    1. Jinal

      24 July, 2011 at 6:36 am

      Is it necessary to write static while declaring constant?
      if we only prefix ‘final’ modifier, then doesn’t it mean the variable is constant?
      Why only final is not enough? Why static is required with final to make constants in java?
       

      Reply
      • Will.Spencer

        24 July, 2011 at 6:55 am

        You can skip ‘static’, but then your variable will only be available when you load an instance of the class where it is defined.  If you always load an instance of that class, you should be fine.

        Reply
    Java
    176 queries in 0.526 seconds.