Feb 7, 2011

Declaring constants in Java J2EE applications

The Java J2EE developers need to declare constants in their applications. Even java game development needs to declare constants. A constant is a value which will not change with time in the lifecycle of a program. They are initialized to some value while declaring them and then the values are used in the program to validate/initialize other variables by java developers. There are a few things which should be kept in mind while writing constants in a java program


  • Declare the constants as public, static and final. This ensures that the java application can use the constants across application without creating an instance of the java class.
  • Declare all constants in a separate java file. This helps in better management of constants in a java application and makes the life of a java developer/java web developer a lot easier.
    All other classes can simply use the name of the constants class to make use of the constants declared.
  • All the characters of a constant should be capitalized. This helps in distinguishing the constant variables from other variables.
    This may not make much sense in terms of declaring the constants in a single java file but it definitely helps when using constants in other java classes.

All these tips can be used in Java application development, java web development and developing web services in java.

3 comments:

  1. good tips. one suggestion is that instead of using class for storing constants its better to use interface because all variable in interface are implicitly public static final and any class can also implement this Constants interface to directly access the constants.

    Thanks
    Javin
    How to detect deadlock in java

    ReplyDelete
  2. good tips. one suggestion is that instead of using class for storing constants its better to use interface because all variable in interface are implicitly public static final and any class can also implement this Constants interface to directly access the constants.

    Thanks
    Javin
    How to detect deadlock in java

    ReplyDelete
  3. Thanks for this useful information.

    ReplyDelete