Final static variable in Java

Utilizing an instance variable when its value is unchanged is not a good idea. We may then apply a static modification to that variable at that point. Whenever we declare the variable static, a single variable is generated at the class level and shared by all the objects. Any modification to that static variable will impact the activities of all other objects. If we don't initialize a static variable, JVM will automatically assign it a default value.

But, while declaring the static variable with the final modifier, we must use the appropriate conventions:

  • If a variable is primarily specified as static, one or more instances of such class where it is declared may modify its value.
  • You may construct a CONSTANT by declaring them to be static final. There is only one copy of the variable, and it cannot be reinitialized.

Important points about the final static variable:

1. Initialization of variable Mandatory

When a static variable is declared as final, it needs to be manually initialized regardless of whether it is used since the JVM will not provide a default value for the final static variable.

Filename: ExampleProgram.java

Output:

error: variable value not initialized in the default constructor

2. Initialization before class loading :

Before class loading is complete, we must execute initialization on the final static variable. A final static variable can be initialized when it is declared.

Filename: ExampleProgram2.java

Output:

56

3. Initialize inside a static block

Since we must create a final static variable before the class and know that the static block is performed before the main() Method, we may also initialize a final static variable inside a static block.

Filename: ExampleProgram.java

Output:

Value of MAX_VALUE: 100

We will obtain a compile-time error if we try to initialize a final static variable somewhere other than the abovementioned techniques.

Filename: ExampleProgram.java

Output:

error: cannot assign a value to final variable value

Implementation of final static variable

Let's see an example where we can use the final static variable.

Filename: Circle.java

Output:

Circle 1 - Radius: 5
Circle 1 - Area: 78.53975
Circle 1 - Circumference: 31.4159
Circle 2 - Radius: 10
Circle 2 - Area: 314.159
Circle 2 - Circumference: 62.8318





Latest Courses