Apr 3, 2012

Define Constants in Java,Conventions for constants

How to define constants in Java


1) The final static modifiers are used for declaring the constants.

2) It is a good practice to add a special class designated for defining constants.

3) The interfaces have their members by default as static and final so they can also be used for defining constants.

4) It is better to use classes for defining constants because interfaces are usually used for defining some contract.

5) The final variables can not be assigned a different value after initialization but the object properties can be modified

6) Values which should be configurable must not be made constant but added to some properties/xml file so that the user can change them without the need to redeploy the application.

7) One should use constants cautiously because the objects which are made final are not garbage collected until the program exits. Though one can suggest garbage collection on constant objects by making the variables as null.

8) The following code shows how to declare constants in Java:

public class MyTest {
public static void main(String[] args) {
System.out.println(Constants.MyConstant);
}
}

class Constants {
public static final String MyConstant = "String1";
}

No comments:

Post a Comment