Question

public class Constants {

    // This is a constant for sure!
    public static final int NUMBER1 = 42;

    // This is a constant.
    public static final Integer NUMBER2 = 42;

     // Is this really a constant?
    public static final BigInteger NUMBER3 = new BigInteger("42");

}

Must a constant necessarily be a primitive [NUMBER1] (or a primitive wrapper [NUMBER2]), or does static final is enough to consider a field as a constant [NUMBER3]?

Was it helpful?

Solution

When you write final Object reference = someObject;, reference is a constant reference to someObject. It will always "point" to that object.

However it does not mean that someObject itself is constant.

For example, in final List list = new ArrayList();, list is a constant that will always refer to the same list, but you can add/remove to that list.

In your example, both Integer and BigInteger are immutable so both the reference and the referenced object are constant.

Note however that the JLS has a precise definition of what constitutes a constant expression, which only includes primitives and String.

OTHER TIPS

I assume you want the actual definition of constant from the language spec and not just the obvious semantics.

$4.12.4. final Variables says the following:

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable

Source

The reason that the JLS defines constants in such a way is because it gives some additional optimization potentials (well it seemed like a good idea at that time):

class Foo {
    public static final int BAR = 5;
}

// other compilation unit
System.out.println(Foo.BAR); 
// compiler is allowed to generate the following code instead:
System.out.println(5); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top