Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to implement constants in Java? [closed]

Tags:

java

constants

People also ask

Should constants be public or private?

You shouldn't always make a constant public or always make it private. To minimize dependencies between classes, you should by default make things private, and only make them protected or public when there is a reason to do so.

Which of the following is a best way to create named constants in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.

Which option is recommended for declaring set of constant variables in Java?

In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters.

Where should I store constants Java?

Even if a constant is used throughout the code but always in relation to one class, it should clearly be part of that class (e.g. BorderLayout. CENTER).


That is perfectly acceptable, probably even the standard.

(public/private) static final TYPE NAME = VALUE;

where TYPE is the type, NAME is the name in all caps with underscores for spaces, and VALUE is the constant value;

I highly recommend NOT putting your constants in their own classes or interfaces.

As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.

For example:

public static final Point ORIGIN = new Point(0,0);

public static void main(String[] args){

    ORIGIN.x = 3;

}

That is legal and ORIGIN would then be a point at (3, 0).


I would highly advise against having a single constants class. It may seem a good idea at the time, but when developers refuse to document constants and the class grows to encompass upwards of 500 constants which are all not related to each other at all (being related to entirely different aspects of the application), this generally turns into the constants file being completely unreadable. Instead:

  • If you have access to Java 5+, use enums to define your specific constants for an application area. All parts of the application area should refer to enums, not constant values, for these constants. You may declare an enum similar to how you declare a class. Enums are perhaps the most (and, arguably, only) useful feature of Java 5+.
  • If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy. This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant)
  • If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them. However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.

It is a BAD PRACTICE to use interfaces just to hold constants (named constant interface pattern by Josh Bloch). Here's what Josh advises:

If the constants are strongly tied to an existing class or interface, you should add them to the class or interface. For example, all of the boxed numerical primitive classes, such as Integer and Double, export MIN_VALUE and MAX_VALUE constants. If the constants are best viewed as members of an enumerated type, you should export them with an enum type. Otherwise, you should export the constants with a noninstantiable utility class.

Example:

// Constant utility class
package com.effectivejava.science;
public class PhysicalConstants {
    private PhysicalConstants() { }  // Prevents instantiation

    public static final double AVOGADROS_NUMBER   = 6.02214199e23;
    public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
    public static final double ELECTRON_MASS      = 9.10938188e-31;
}

About the naming convention:

By convention, such fields have names consisting of capital letters, with words separated by underscores. It is critical that these fields contain either primitive values or references to immutable objects.


In Effective Java (2nd edition), it's recommended that you use enums instead of static ints for constants.

There's a good writeup on enums in Java here: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

Note that at the end of that article the question posed is:

So when should you use enums?

With an answer of:

Any time you need a fixed set of constants