Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Simply put, static final variables, also called constants, are key features in Java to create a class variable that won’t change after initialization. However, in the case of a static final object reference, the state of the object may change.

In this tutorial, we’ll learn how to declare and initialize constant variables. Also, we’ll discuss their usefulness.

2. static final Variables

The static keyword associates a variable to a class itself, not to instances of the class.

Furthermore, the final keyword makes a variable immutable. Its value can’t change after initialization.

The combination of the two keywords helps create a constant. They are mostly named using uppercase and underscores to separate words.

2.1. Initializing static final Variables

Here’s an example of how to declare a static final field and assign a value:

class Bike {
    public static final int TIRE = 2;
}

Here, we create a class named Bike with a constant class variable named TIRE and initialize it to two.

Alternatively, we can initialize the variable via a static initializer block:

public static final int PEDAL;
static {
    PEDAL = 5;
}

This will compile without an error:

@Test
void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() {
    assertEquals(5, Bike.PEDAL);
}

Here are some key rules for constant variables:

  • We must initialize upon declaration or in a static initializer block
  • We can’t reassign it after initialization

Attempting to initialize it outside the initialization scope will cause an exception.

Also, we can’t initialize it via the constructor because constructors are invoked when we create an instance of a class. Static variables belong to the class itself and not to individual instances.

2.2. static final Objects

We can also create static final object references:

public static final HashMap<String, Integer> PART = new HashMap<>();

Since the PART reference is constant, it can’t be reassigned:

PART = new HashMap<>();

The code above throws an exception because we assign a new reference to an immutable variable.

However, we can modify the state of the object:

@Test
void givenPartConstantObject_whenObjectStateChanged_thenCorrect() {
    Bike.PART.put("seat", 1);
    assertEquals(1, Bike.PART.get("seat"));
    Bike.PART.put("seat", 5);
    assertEquals(5, Bike.PART.get("seat"));
}

Here, we can change the value of the seat despite setting it to one initially. We mutate the contents of PART despite being a constant reference. Only the reference itself is immutable.

Notably, the final keyword only makes primitive types, String, and other immutable types constant. In the case of an object, it only makes the reference constant, but the state of the object can be altered.

3. Why Constants Are Useful

Using static final variables has several advantages. It provides better performance since its values are inlined at compile time instead of a runtime value lookup.

Moreover, declaring reusable values as constant avoids duplicating literals. Constant can be reused anywhere in the code, depending on the access modifier. A constant with a private access modifier will only be usable within the class.

Additionally, a static final variable of primitive or String type is thread-safe. Its value remains unchanged when shared among multiple threads.

Finally, giving semantic names to constant values increases code readability. Also, it makes code self-documenting. For example, the java.math package provides constants like PI:

@Test
void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() {
    assertEquals(3.141592653589793, Math.PI);
}

The Math.PI encapsulates the mathematical constant value in a reusable way.

4. Conclusion

In this article, we learned how to declare and initialize a constant variable. Also, we highlighted some of its use cases.

A final static variable defines a class-level constant. However, a static final object may still be mutable, even if the reference can’t change.

As always, the complete source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!