What is the best practice to declare a java file having only constant?
public interface DeclareConstants
{
String constant = \"Test\";
}
OR
This question is old. But I would like to mention an other approach. Using Enums for declaring constant values. Based on the answer of Nandkumar Tekale, the Enum can be used as below:
Enum:
public enum Planck {
REDUCED();
public static final double PLANCK_CONSTANT = 6.62606896e-34;
public static final double PI = 3.14159;
public final double REDUCED_PLANCK_CONSTANT;
Planck() {
this.REDUCED_PLANCK_CONSTANT = PLANCK_CONSTANT / (2 * PI);
}
public double getValue() {
return REDUCED_PLANCK_CONSTANT;
}
}
Client class:
public class PlanckClient {
public static void main(String[] args) {
System.out.println(getReducedPlanckConstant());
// or using Enum itself as below:
System.out.println(Planck.REDUCED.getValue());
}
public static double getReducedPlanckConstant() {
return Planck.PLANCK_CONSTANT / (2 * Planck.PI);
}
}
Reference : The usage of Enums for declaring constant fields is suggested by Joshua Bloch in his Effective Java book.